Get attachment ID by its thumbnail URL in WordPress
Published: – Leave a comment
Working with attachments in WordPress is always somewhat special to me, because I always learn something new about its handling. In this case, I needed to get the attachment ID of an attachment via one of its thumbnail URL.
There is a function attachment_url_to_postid
, which is similar to url_to_postid
, but specifically for attachments (since url_to_postid
didn’t work here). So I first thought I can just use my thumbnail URL as parameter to attachment_url_to_postid
and it will work. Unfortunately, it didn’t.
Looking into the code of this function made it clear to me very fast: this function only checks the postmeta fields of _wp_attached_file
, which is the original attachment file. So there is no support for thumbnails here.
My solution
My approach to still be able to use this was in just removing the dimensions from the filename to get the original one. Assuming I’ve uploaded the image my-image.jpg
, my thumbnail would be called my-image-1024x768.jpg
. So I would have to remove the -1024x768
from the filename just before the file extension.
So this is how my code looks like:
$image = 'https://domain.tld/wordpress/2023/05/my-image-1024x768.jpg';
// replace dimensions from image
$image = \preg_replace( '/\-\d+x\d+\.(jpe?g|png|gif)$/', '.$1', $image );
$post_id = \attachment_url_to_postid( $image );
Code language: PHP (php)
I replace any combination of -<digits>x<digits>
right before the file extension. Since in my case I somewhat know which file extensions I’m working of, I just added them to the regular expression to limit the possibility of wrong replacements.
This solution will replace the thumbnail URL with the URL of the originally uploaded file and thus will be able to find the attachment ID via attachment_url_to_postid
.