Get Attachment ID from media_sideload_image()


In this scenario,

The $image variable now returns the full HTML, like this (with single quotes for some reason)

Which isn’t so bad, unless we want to get Just the image URL, or maybe the Thumbnail URL, or just the attachment ID.
Here is how to do it.

Getting the plain Image URL is quite simple, just requires a little bit of REGEX.

Now it’s a little more trickier to get the attachment ID, because it isn’t enough to just simply ask for “url_to_postid($url);” as it would work with posts and pages. So I found this neat function in wordpress forums

And now when we put it all together, it looks something like this:



  • My solution was to just copy the media_sideload_image function into my own plugin, rename the function, and have it return the attachment id rather than the html.

    Also, FYI, I got a little error with your preg_replace in the code above.

    • Hey Devin,
      I didn’t think of that. It actually may be an even better solution. At the time of writing this post I was more or less (or more) excited about using Regex everywhere, so I might have an agenda for this approach.

      What was the little error ?

  • Here’s the correct regex expression:
    $image = preg_replace(‘/.*(?<=src=["\'])([^"\']*)(?=["\']).*/', '$1', $image);

  • Thanks for the article, it helped in some ways. I don’t know if this feature was available at the time you authored this article, but you can use a 4th argument in the following way: “media_sideload_image($url, $id, $description, ‘src’)” this will return the image’s URL rather than HTML output.

  • Why not use $wpdb->insert_id?

    Eventual media_side_image falls back to runs $wpdb->insert so it is globally available e.g.

    global $wpdb;

    media_sideload_image( $url, $example_id);

    $file_id = $wpdb->insert_id;

    • I never thought of that! Are you sure it’s bulletproof? That would render this article completely useless 😅

Leave a Reply

Your email address will not be published. Required fields are marked *