WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);

share|improve this question

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.