Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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 );
share|improve this answer
    
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? –  Miloshio Nov 5 '12 at 14:21
add comment

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

share|improve this answer
add comment

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 );
share|improve this answer
add comment

Your Answer

 
discard

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.