Programmatically adding images to the media library with wp_generate_attachment_metadata randomly fails

I have checked your code, and I think you are missing the guid of the images. Please have a look at the code below:


$post_id = 1234;
$images = array('filename1.png', 'filename2.png', ... 'filename10.png');

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

foreach($images as $name) {
    $attachment = array(
        'guid'=> $wp_upload_dir['url'] . "https://wordpress.stackexchange.com/" . basename( $name ), 
        'post_mime_type' => 'image/png',
        'post_title' => 'my description',
        'post_content' => 'my description',
        'post_status' => 'inherit'
         );
$image_id = wp_insert_attachment($attachment, $name, $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( $image_id, $name );
wp_update_attachment_metadata( $image_id, $attach_data );
}

For detail look the wp_insert_attachment function.

Leave a Comment