Get $image_id after uploading with media_sideload_image()

I want to upload an 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?


Here is an example of how to bypass this limitation using actions/hooks:

function new_attachment( $att_id ){
    // the post this was sideloaded into is the attachments parent!

    // fetch the attachment post
    $att = get_post( $att_id );

    // grab it's parent
    $post_id = $att->post_parent;

    // set the featured post
    set_post_thumbnail( $post_id, $att_id );

// add the function above to catch the attachments creation

// 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 

The idea is that when media_sideload_image is ran, it:

  • downloads the image
  • adds it as an attachment ( a post of type attachment )
  • then attaches that attachment 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 its ID. We can hook into this before we create the attachment, and save the featured thumbnail with the post ID it gave us, then unhook afterwards.

Leave a Comment