For various reasons, I can’t use WordPress’ built-in Thumbnail functionality.

What I want to do instead is to use the first image in the post as the thumbnail.

Here’s what I found in the codex: Show the first image associated with the post.

However, the problem with that is that if the post has multiple images, but the first image in the post is not actually the one that was uploaded first, you’ll end up getting the second image instead of the first one.


So, I decided to use something similar to this approach, which uses a regex to parse the_content to find the first post.

This works out fine, but I end up with the image size that was used in the post, and I only want the Thumbnail size.


So, here’s the question: If I have a link to an image, is there any way I can get a different size?

Seems what I need is to somehow get the attachment ID, so that I can get the image size with this:

wp_get_attachment_link( $id, 'thumbnail' );

The problem is, how do I get an ID if all I have is the URL?

3 Answers
3

I decided to use this, which is based on @AndresYanez’s answer:

function get_image_id_by_link($link)
{
    global $wpdb;

    $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $link);

    return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE BINARY guid='$link'");
}

This is much more succinct (since it doesn’t jump through the hoops of first removing the extension and then adding it back in), and is a little more accurate (since the . is escaped and the query is case sensitive).

Leave a Reply

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