I'm using wp_insert_post and media_sideload_image to create a post and attach a single image to the post. However, how can I mark this attached image as featured thumbnail? It would make listing the thumbnails significantly faster by using the_post_thumbnail instead of looping through each post manually showing the first image.

How can I mark the attached image as featured thumbnail?

Thanks, Dennis

1 Answer 1


Perhaps use set_post_thumbnail()? (Codex ref.)


To get the attachment ID using the Post ID:

// Associative array of attachments, as $attachment_id => $attachment
$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );

$attachment = $attachments[0]; // ID of your single, attached image.

Then to set it as the featured image:

set_post_thumbnail( $attachment );

I have to check to be sure; the docs are a bit confusing. The default output might be an object. Regardless, get_children() will get you to the ID of your lone attachment, given the Post ID.

  • Hi Chip, excellent choice, but I've been so far unable to find the actual attachment or thumbnail ID of the image, any idea on how to get it?
    – FLX
    Commented Jun 22, 2011 at 15:20
  • Do you have the ID of the Post? Commented Jun 22, 2011 at 18:51
  • Yup, I sure do :)
    – FLX
    Commented Jun 22, 2011 at 20:28
  • See updated answer. :) Commented Jun 22, 2011 at 21:05
  • I tried this but it didnt work, as the array number is not 0 but the actual ID of the attachment: attachmentID: Array ( [266] => stdClass Object ( [ID] => 266 [post_author] => 1 [post_date] => 2011-06-23 11:44:18 [post_date_gmt] => 2011-06-23 09:44:18 In other words, I need to find a way to get this ID in order to properly parse it.
    – FLX
    Commented Jun 23, 2011 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.