How to add/assign or change featured image in post programmatically?

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.

4 Answers
4

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

Leave a Comment