We all know you can use wp_get_attachment_url() to return an attachment’s URL by passing in the ID, but what about the reverse scenario?
There are a lot of long-winded examples of how to get an attachment ID by URL floating around the interwebs. Most of them limit results to only returning images or use expensive DB queries. Really, there should be a function for this in core, but there isn’t.
Needless to say, I wasn’t really happy with any of the solutions I found people using, so I decided to take a stab at it.
Below is the most lightweight method I’ve come up with (so far) to get an attachment ID by passing through an attachment URL.
Just as an example, this would echo the attachment ID integer of
test-image.jpg onto the page:
This would echo the same result as above because we are ignoring
www usage in the URL being passed through:
This would echo nothing, because the image doesn’t exist in the WordPress uploads directory:
And finally, this would also echo nothing because the URL of the file is pointing to an external domain:
We managed to fetch an attachment ID in just a few lines of code with no expensive DB queries! Awesome
Now you can do cool things like turn a URL into an absolute path:
For more information about what was used in this function, please see:
Was this code helpful to you? Let me know in the comments!