Retrieve Attachment ID from Image URL410

Author: InfoBeep - August 3, 2017 | subject to copyright

Especially when developing plugins or theme settings that make use of the WordPress media uploader to upload and insert images, being able to retrieve the ID of the image uploaded can be extremely useful. By grabbing the image (attachment) ID, you suddenly have a lot more control over what you can do with the image, such as display one of the different sizes that WordPress generates when the image is uploaded.

This is a little function I wrote while on the train home from Chicago.

// retrieves the attachment ID from the file URL
// retrieves the attachment ID from the file URL

function pippin_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 of the image ID you wish to retrieve. Once you’ve done that, you could do the following to retrieve the auto-generated thumbnail size of the image:

 

// set the image url
$image_url = ‘https://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg’;

// store the image ID in a var
$image_id = pippin_get_image_id($image_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];

 

I love this article thank you https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

Thank you, my viewers, for reading this article 1624 times. Thank you for your love and support.
By: Infobeep.info