Retrieve Attachment ID from Image URL

February 22, 2014 in Snippets

What if you only have image URL, but you need attachment ID or different size of image? WordPress by default don’t have a function for retrieve attachment ID from Image URL, but with a few lines of code you can solve it

function get_image_id_by_url($image_url) {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $image_url ));
    return $attachment[0];
}

Usage in theme or plugin

$image_id = get_image_id_by_url($image_url);
$image_thumb = wp_get_attachment_image_src($image_id, 'thumb-size');
echo '<img src="'.$image_thumb[0].'">';