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(
   'article1.jpg',
   'article2.jpg',
);

// 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'] . "https://wordpress.stackexchange.com/" . 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 );

}

3

$image_url="adress img";

$upload_dir = wp_upload_dir();

$image_data = file_get_contents( $image_url );

$filename = basename( $image_url );

if ( wp_mkdir_p( $upload_dir['path'] ) ) {
  $file = $upload_dir['path'] . "https://wordpress.stackexchange.com/" . $filename;
}
else {
  $file = $upload_dir['basedir'] . "https://wordpress.stackexchange.com/" . $filename;
}

file_put_contents( $file, $image_data );

$wp_filetype = wp_check_filetype( $filename, null );

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

$attach_id = wp_insert_attachment( $attachment, $file );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

Leave a Comment