Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. giovanemachado revised this gist Aug 23, 2019. No changes.
  2. giovanemachado created this gist Aug 23, 2019.
    50 changes: 50 additions & 0 deletions Adicionando imagens no wordpress programaticamente
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    // Caminho do servidor
    $where_read = ABSPATH . 'caminho/para/os/arquivos';

    // Pega apenas arquivos, ignorando o que não tiver extensão ( pastas )
    $files_array = glob( $where_read . "/*.{*}", GLOB_BRACE );
    $upload_dir = wp_upload_dir();

    foreach( $files_array as $file ):

    /**
    *
    * $file aqui tem que ser o caminho completo no servidor (/home/[dominio]/public_html/wp-content/uploads/arquivo.jpg)
    *
    */
    $image_url = $file;
    $image_data = file_get_contents( $image_url );
    $filename = basename( $image_url );

    if ( wp_mkdir_p( $upload_dir['path'] ) ) {

    $file = $upload_dir['path'] . '/' . $filename;

    } else {

    $file = $upload_dir['basedir'] . '/' . $filename;

    }

    file_put_contents( $file, $image_data );

    $wp_filetype = wp_check_filetype( $filename, null );

    $attachment = [

    'post_mime_type' => $wp_filetype['type'],
    'post_title' => sanitize_file_name( $filename ),
    'post_content' => '',
    'post_status' => 'inherit'

    ];

    // Armazena os ids dos attachments.
    $attach_id[] = wp_insert_attachment( $attachment, $file );
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Gera os metadatas necessários para que os attachments funcionem normalmente.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    endforeach;