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

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer
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 Jun 22 '11 at 15:20
Do you have the ID of the Post? – Chip Bennett Jun 22 '11 at 18:51
Yup, I sure do :) – FLX Jun 22 '11 at 20:28
See updated answer. :) – Chip Bennett Jun 22 '11 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 Jun 23 '11 at 9:46

Your Answer


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

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