How to add a featured image to a existing post via php?

The trick is media_sideload_image() and set_post_thumbnail(). media_sideload_image() assumes you can grab the URL to the image, whether it exist in /wp-content/ or somewhere else (another site, even). As long as you can programmatically reference the image’s URL, something like this should work.

$image="image.jpg";
$media = media_sideload_image($image, $post->ID);
if(!empty($media) && !is_wp_error($media)){
    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => 1,
        'post_status' => 'any',
        'post_parent' => $post->ID
    );

    // reference new image to set as featured
    $attachments = get_posts($args);

    if($attachments){
        foreach($attachments as $attachment){
            set_post_thumbnail($post->ID, $attachment->ID);
            // only want one image
            break;
        }
    }
}

Leave a Comment