WordPress – Get Attachment Id through Image url

Aug 23, 2012 | Blog |

There are many cases we might require the attachment id using the image path. Use the below function in functions.php of theme.

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

And to get the ID

$attachment_id = kd_get_attachment_id('http://path of the image');

If you want to grab a specific size of the attachment try

wp_get_attachment_image_src( $attachment_id, $size );

so $size can be thumbnail,full or custom size

To grab the url of the custom size

$attachment = wp_get_attachment_image_src( $attachment_id, 'custom_size' );

echo $attachment[0];