4
votes

I'm programmatically uploading images to my Wordpress media gallery and setting them as my post's featured image, which is working quite well.

I'd like to generate thumbnails of these featured images, in the same way that Wordpress handles creating resized thumbnails when an image is added through the Insert Media pane, where it creates multiple files, each with the new dimensions specified in the file name.

Unfortunately, I'm having a lot of trouble locating anything that explains how this would be done properly.

Below is the relevant code. It successfully creates the post and sets the featured image to the media file, but doesn't generate thumbnails to go with it.

Any help would be greatly appreciated!

// If the post was created
if($post_id) {

    // Add meta/custom field data
    add_post_meta($post_id, 'gif_random_id', $randomId);

    // Add uploaded file to the actual Wordpress image library
    global $uploadURL;
    $filename = $uploadURL . $randomId . '.' . $fileExtension;
    $wp_filetype = wp_check_filetype(basename($filename), null);
    $wp_upload_dir = wp_upload_dir();

    $attachment = array(
        'guid' => $wp_upload_dir['url'] . '/' . basename($filename), 
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
        'post_content' => '',
        'post_status' => 'publish'
    );

    $attach_id = wp_insert_attachment($attachment, $filename, $post_id);

    $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
    wp_update_attachment_metadata($attach_id, $attach_data);

    // Now set the attachement as the featured image
    update_post_meta($post_id, '_thumbnail_id', $attach_id);

}
2

2 Answers

5
votes

You should use another - rather unknown and misunderstood function- media_sideload_image()

 $attach_id = media_sideload_image($filename, $post_id);

This function will handle the "upload" process and will follow the normal workflow of uploading images to wordpress which includes thumbs generation as defined in your custom image sizes

-3
votes

Kaput, your code is perfectly fine, but seems your initial image is not in the uploads folder. See what the documentation says:

Location of the file on the server. Use absolute path and not the URI of the file. The file MUST be on the uploads directory. See wp_upload_dir().

Just make sure you upload the image in the uploads directory first.