I’m creating a custom CSV importer for a client and the pictures are added, however the thumbnails aren’t being generated properly. After using a plugin like Regenerate Thumbnails they do show correctly.
Here is the code in which I add the attachment and link it to the post.
$uploadDir = 'wp-content/uploads/importedproductimages/';
$siteurl = get_option('siteurl');
$thumbnail = 'importedproductimages/' . $name;
$filename = 'importedproductimages/' . $name;
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_content' => '',
'post_status' => 'inherit',
'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$uploadDir.$name
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $thumbnail );
wp_update_attachment_metadata( $attach_id, $attach_data );
// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);
Why aren’t the thumbnails being generated properly?
Thank you in advance.
EDIT:
I have also included image.php like so:
require_once(ABSPATH . 'wp-admin/includes/image.php');
This ended up working for me:
Old question I know, but this came up on Google in my searches for the answer, and there is a better way to generate the thumbnails, as well as any other image sizes needed: wp_generate_attachment_meta. Used in two lines:
This refreshes ALL image sizes, including Thumbnails, when given an attachment ID.