How can I get a different image size, if all I have is the link?

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 Comment