Get attachment thumbnail path by its URL in WordPress
Published: – Leave a comment
In my last post I tracked down how to get the attachment ID of an attachment by one of its thumbnail URLs. Today, I go a step beyond that and show how to get the thumbnail path by its URL.
The approach starts similar to the previous one since we first need to get the post ID of the attachment. For further details on that, please read my previous post. We then use a very similar regular expression but with a named group to get access to the actual dimension of the thumbnail into the array index dimension
.
After that, we can use the builtin function image_get_intermediate_size
to get the relative path to the thumbnail and concatenate it with the upload directory.
Additionally, since it may happen in my case that I don’t just pass thumbnails to this functionality but also the full image, I checked whether the URL actually contains a thumbnail dimension.
This is what the code looks like:
$image = 'https://domain.tld/wordpress/2023/05/my-image-1024x768.jpg';
// replace dimensions from image
$attachment_url = preg_replace( '/\-\d+x\d+\.(jpe?g|png|gif)$/', '.$1', $image );
// get the post ID of the attachment
$post_id = \attachment_url_to_postid( $attachment_url );
$size = '';
\preg_match( '/\-(?<dimension>\d+x\d+)\.(jpe?g|png|gif)$/', $image, $matches );
// if we got a dimension, store the size as array, width as first array key, height as second
if ( ! empty( $matches['dimension'] ) ) {
$size = \explode( 'x', $matches['dimension'] );
}
if ( $size ) {
// it's a thumbnail, so get its thumbnail path
$image = \wp_upload_dir()['basedir'] . '/' . \image_get_intermediate_size( $post_id, $size )['path'];
}
else {
// it's the full image, just get its path
$image = \get_attached_file( $post_id );
}
Code language: PHP (php)