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 want to upload a image and set it as a featured image in a post. What i tried was this:

$image_id = media_sideload_image($image_url, $post_id, $post_id);
update_post_meta($post_id, '_thumbnail_id', $image_id);

But media_sideload_image() is not returning the image_id, but the render html image. How can I get the image_id??

share|improve this question

1 Answer 1

Here's code that should serve as an example on how to bypass this limitation using action hooks:

function new_attachment($att_id){
    // the post this was sideloaded into is the attachments parent!
    $p = get_post($att_id);
    update_post_meta($p->post_parent,'_thumbnail_id',$att_id);
}

// add the function above to catch the attachments creation
add_action('add_attachment','new_attachment');

// load the attachment from the URL
media_sideload_image($image_url, $post_id, $post_id);

// we have the Image now, and the function above will have fired too setting the thumbnail ID in the process, so lets remove the hook so we don't cause any more trouble 
remove_action('add_attachment','new_attachment');

The premise is that when media_sideload_image is ran, it downloads the image, adds it as an attachment, then attaches that attachment post to the post whose ID you provided($post_id). Your issue is that it does not provide the newly created attachment posts ID, but, when an attachment is created, an action is fired containing that ID, and from that we can figure out the ID of the post ($post_id), and set the featured image.

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.