Programmatically adding images to media library


I am trying to programmatically add multiple images to media library, I uploaded the images to wp-content/uploads, now I try to use wp_insert_attachement.

Here’s the code, however it’s not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.

$filename_array = array(

// The ID of the post this attachment is for.
$parent_post_id = 0;

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

foreach ($filename_array as $filename) {

    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );

    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

    // Make sure that this file is included, as   wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

, , Adrian 3 years 2020-07-18T23:10:38-05:00 0 Answers 65 views 0

Leave an answer