Just another WordPress site

Get the WordPress post attachment ID from an Image Src

This function returns the wordpress attachment ID of a given image src. Useful if you need to get a different size version of the same image. Snippet from jameslafferty @ http://wordpress.org/support/topic/need-to-get-attachment-id-by-image-url

UPDATED: to include refinements, see comments below. This will work with image urls that have been resized by WordPress also.

function get_attachment_id_from_src ($link) {
	global $wpdb;
        $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $link);
        return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$link'");
}

//Get a different size image
    $attachment_id = get_attachment_id_from_src( $src );
    $medium_im = wp_get_attachment_image_src( $attachment_id, 'medium');
//wp_get_attachment_image_src() is a wordpress function that returns an array with {src, width,height}  info.
echo '<img src="'.$medium_im[0].'" alt="" width="'.$medium_im[1].'" height="'.$medium_im[2].'" />';

6 Comments to Get the WordPress post attachment ID from an Image Src

  1. mattl's Gravatar mattl
    June 22, 2011 at 11:59 am | Permalink

    How do you get this to work if the src you are working with has size details in it like -300×200.jpg

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>