Get Image ID from Image URL – WordPress

Get Image ID from Image URL in wordpress. Get other image sizes by providing image URL. Get intermediate image sizes from image URL.

While developing plugins and themes you need to get multiple sizes of the images. Especially when you need smaller sizes of the image according to need. What if you need to get image ID from image URL?.

The URL of the image can grab you the ID of the image. WordPress generates different type of image sizes and suppose you want thumbnail instead of bigger image to reduce load time.

While working with this theme you see on our website we take similar approach. Learn how to get image id from image URL in wordpress.

Image ID from Image URL

paste the below function to functions.php

// retrieves the attachment ID from the file URL
function two_get_image_id($image_url) {
	global $wpdb;
	$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
        return $attachment[0]; 

Simply pass the URL parameter of image to get the ID against that image. The idea behind this is to call another size image according to need.

// set the image url
$img_url = '';
// store image id in variable
$image_id = two_get_image_id($img_url);
// retrieve the thumbnail size of our image
$image_thumb = wp_get_attachment_image_src($image_id, 'thumbnail');
// display the image
echo $image_thumb[0];

Leave a Reply

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