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'm having trouble to add a featured image to an existing post via PHP. The image resides on wp-content/upload folder. The script i'm doing, is not a plugin, theme, or something like that. It's just an automation script that runs whenever it's called.

What is the best approach for this case?

share|improve this question
    
Post your code please. Where is the code located? And when/how is it "called"? –  s_ha_dum Jan 15 at 20:32

1 Answer 1

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;
        }
    }
}
share|improve this answer

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.