Get Attachment ID from a WordPress Image URL

Taking a WordPress image URL and using it to get the attachment ID is a bit tricky. There are a lot of code samples out there that do this, but they all have problems to some degree or another.

Pippin Williamson posted a very elegant solution based on comparing the URL to the guid in the WordPress database, but that doesn’t really work if the guid gets out of sync or if the URL you have is for a cropped image.

Phillip Newcomer realized that relying on the guid wasn’t the best route and that there should be a way to get the attachment ID even when you have a cropped image URL. So, he wrote some code that strips off the image dimensions that WordPress adds to the end of the file names and then checks the resulting filename against the _wp_attached_file meta key in the database. This works well, most of the time. However, the filename after stripping off the image dimensions doesn’t always match the value of _wp_attached_file, so in those cases it fails.

If we look to WordPress StackExchange, we’ll find code written by Andrey Savchenko (a.k.a. “Rarst”) that predates both of the solutions above and actually overcomes all the issues which were previously mentioned. In fact, my solution is largely inspired by the code he wrote. The only issue with the solution he provided is that there are potentially two queries performed to find a single attachment ID.

My solution was to use the robust and sound logic that Rarst used, but to do the same work using only a single query:

So, the next time you are Googling for a code solution, don’t just use the first code sample you find… even if it works for you. Find some alternate solutions. Read the code and think about use cases where it might break. Most importantly, learn what the code does and don’t just copy and paste. We don’t need to perpetuate bad solutions out of convenience.

I’d like to challenge you to always find one thing you can improve when you decide to use a code snippet. In fact, start with mine… how would you improve it?

5 thoughts on “Get Attachment ID from a WordPress Image URL”

    1. If it is for a different protocol, then you would probably want to do a search and replace to update those instances in your database anyway. If it is a different domain, then you wouldn’t have that attachment in your database. The exception to those use cases as well as the port / auth would be if you are working on a site locally. In this case, you’ll probably want to adapt the function above so you can check against an alternate uploads URL.

Leave a Reply

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