Get Attachment ID from media_sideload_image()

Problem

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:

 

 

7 thoughts on “Get Attachment ID from media_sideload_image()”

  1. 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.

    1. 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 ?

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

  3. 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.

Leave a Reply

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