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
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 = 'http://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];

Enjoy!

  1. thetrickster

    I have issues sometimes where we have a site that has been on a different primary domain before we took over and the GUID doesn’t always have the same hostname. For our situation, we used an updated version of this code to do a regex search for the guid using a relative URL.

    ““
    function pippin_get_image_from_id( $url ) {
    // Makes a relative link by removing hostname
    $url = wp_make_link_relative( $url );
    global $wpdb;
    // Using RLIKE operation to do regex search
    $query = “SELECT ID FROM {$wpdb->posts} WHERE guid RLIKE ‘$url'”;
    return $wpdb->get_var($query);
    }
    ““

    We’ve recently begun testing this out– I will let you know if i run into issues with returning multiple values from query or something like that.

Leave a Reply

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match