I have written a plugin that (besides other functionality) makes posts from existing content. For each post I have one picture - how to make them featured programmatically?

I do the:

$id =  wp_insert_post( $my_post );
wp_set_object_terms( $id, $cat_ids, 'category' );

and I would like my next step to be inserting $image (file path or URI) as featured image. How?

Thanks in advance.

3 Answers 3


Try using set_post_thumbnail().

Assuming you already know how to determine the $post (ID or object) for which to set the featured image, and the $thumbnail_id (ID) of the image that you want to set as the featured image:

set_post_thumbnail( $post, $thumbnail_id );
  • Chip, thanks very much, I've assumed that such function exists, but how do I get $thumbnail_id which is integer, and I've expected file path or URL string? Commented Nov 5, 2012 at 14:21

set_post_thumbnail will allow to set 1 attachment from id to a post of provided id.

If you don't have the attachment id or want to do it directly from url, you will have to create the attachment first, see wp_insert_attachment

you may also upload the image using media_sideload_image


You can use wp_insert_attachment() and wp_generate_attachment_metadata() to make the image an attachment to the post. And you make it a featured image by using set_post_thumbnail(). (it's really just a custom field _thumbnail_id.
Something like:

$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 );
set_post_thumbnail( $post_id, $attach_id );

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.