Get a WordPress Image’s Attachment ID from its URL with a PHP Function from Pippin Williamson

pippin's plugins | retrieve image id from url
EDIT: As the comments below have pointed out, WordPress in later versions contains the attachment_url_to_postid() function, which is designed to do the job of the code below. However, on at least one project I’ve worked on (a WordPress multisite), WordPress’s function didn’t work and Pippin’s did. I’d try the WordPress function first and Pippin’s as a fallback.

You know who’s really great? Pippin Williamson.

For a recent client project, I needed to programmatically find out a set of WordPress images’ IDs from their URL. Google led me to some very helpful code Pippin wrote way back in 2011:

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]; 

Visit the link to see a quick code example from Pippin that uses the pippin_get_image_id() function.

And if you haven’t paid your 2017 Pippin Is Awesome tax directly to his house, remember that the deadline is May 15.

3 Responses


Add a Comment

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