Get Attachment ID from Image URL – WordPress

Featured image URL is required while developing plugin and themes to best fit for background image. image size of featured image Fetching default featured image in wordpress is easy but when you need to call another size of image you need attachment id of that featured image. Learn how to get attachment ID from image URL in WordPress ?.

The URL of featured image can get attachment ID from image URL. In last we describe the idea and the benefits of using calling different image sizes in wordpress. image size of featured image

Attachment ID from Image URL

paste the below code in functions.php to register a function. Later on we just need to pass a url to pp_get_image_id(url of image) and it will get us the id of the image.
// retrieves the attachment ID from url
function pp_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]; 
}
Just for illustration, use an image from media library or your wordpress. Read how to get the featured image url in wordpress.Simply pass the URL parameter of image to get the ID against that image. The idea behind this is to call another size image.
// Image url to get the ID of
$img_url = 'http://propatel.com/wp-content/uploads/2011/02/14/image_name.jpg';
 
// store image id in variable
$image_id = pp_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];

Benefits to get attachment id: When you want an image in background of "DIV" but not the featured image. wp_get_attachment_url will provide the url of the attachment url to postid. Suppose you get attachment path or url which is larger then your requirement. We suggest to call thumbnail or medium size by above method to reduce load time.

Why attachment ID from image is used?

Attachment ID from image URL is used to incorporate other size of image in wordpress themes or plugin. Read How to register different image sizes in wordpress or set default image sizes from settings > media in wordpress (e.g. large, medium, thumbnail).

How Image Sizes in WordPress Affect SEO:


Usually, a developer needs to reduce load time of page, to get higher percentage in google speed test. As in SEO the bigger the image size the chances of page load to be increased. While working with a theme, i realize why not to use smaller image size to reduce the load time for higher ranking.

Post a Comment

0 Comments