I'm uploading images to my 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);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.