Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Retrieve Attachment ID from Image URL

Posted on September 4, 2011 by Pippin in Intermediate, Quick Tips, Tutorials, Working with Attachments 21 Comments
Home» Tutorials » Intermediate » Retrieve Attachment ID from Image URL
Tweet
Love It - 2

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 quick tip. Check out more Quick Tips

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

1
2
3
4
5
6
7
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
	global $wpdb;
	$prefix = $wpdb->prefix;
	$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM " . $prefix . "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:

1
2
3
4
5
6
7
8
9
10
11
// 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!

Tweet Follow @pippinsplugins
attachment, images, thumbnail

21 comments on “Retrieve Attachment ID from Image URL”

  1. Chris says:
    September 4, 2011 at 5:30 pm

    Does it work with image URLs that are not the main image? Resized versions, etc.

    Reply
    • Pippin says:
      September 4, 2011 at 10:34 pm

      No, you will need the original URL, but you can then use the ID to get the other sizes.

  2. AJ says:
    September 5, 2011 at 2:04 pm

    Very useful. Great work!

    Reply
  3. Duane says:
    August 6, 2012 at 7:27 am

    Hey Pippin,

    This is a rad little snippet. I rewrote it slightly to directly retrieve the desired thumb size as it can become frustrating to continually rewrite the last 3 steps.

    function pippin_get_image_id( $image_url, $size ) {
     
    	global $wpdb;
    	$prefix = $wpdb->prefix;
    	$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM " . $prefix . "posts" . " WHERE guid='" . $image_url . "';" ) );
    	$image_thumb = wp_get_attachment_image_src( $attachment[0], $size );
    	return $image_thumb[0];
    }
    Reply
    • Pippin says:
      August 6, 2012 at 12:07 pm

      Excellent!

  4. Ruven says:
    October 2, 2012 at 1:22 pm

    I tried this out, but it seems that the “guid” is not in all cases the URL to the picture.

    Reply
    • Pippin says:
      October 3, 2012 at 12:19 am

      That is true, the guid column will not always work. There was a tutorial someone posted not too long ago with a better way to do this, but I don’t remember which site it was on unfortunately.

    • Philip Newcomer says:
      November 7, 2012 at 10:43 am

      After combining some code from several other people who have posted about this online, here’s a function I wrote that doesn’t use GUIDs, and even works with image thumbnail URLs:

      function pn_get_attachment_id_from_url( $attachment_url = '' ) {
       
      	global $wpdb;
      	$attachment_id = false;
       
      	// If there is no url, return.
      	if ( '' == $attachment_url )
      		return;
       
      	// Get the upload directory paths
      	$upload_dir_paths = wp_upload_dir();
       
      	// Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
      	if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
       
      		// If this is the URL of an auto-generated thumbnail, get the URL of the original image
      		$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
       
      		// Remove the upload path base directory from the attachment URL
      		$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
       
      		// Finally, run a custom database query to get the attachment ID from the modified attachment URL
      		$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );
       
      	}
       
      	return $attachment_id;
      }
  5. Get the Attachment ID from an Image URL in WordPress - Philip Newcomer says:
    November 7, 2012 at 10:24 am

    [...] no built-in function in WordPress for doing this, and a Google search provided only partial solutions, or solutions that didn’t work with thumbnail images. However, using some [...]

    Reply
  6. Philip Newcomer says:
    November 7, 2012 at 10:46 am

    Looks like the comment form tag doesn't format the text nicely. Here's my blog post with the code formatted for easier reading: http://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/

    Reply
    • Pippin says:
      November 7, 2012 at 10:49 am

      Looks great! FYI, you can post code by wrapping it in PRE tags.

    • Philip Newcomer says:
      November 7, 2012 at 10:55 am

      I see. The PRE tag wasn’t in the list of allowed tags below the comment box, so I used CODE. :)

  7. Melinda says:
    December 12, 2012 at 11:12 pm

    I am using this and just upgraded to WP 3.5. Now I get this error: Warning: Missing argument 2 for wpdb::prepare(),. I found the post about how it should work now (http://make.wordpress.org/core/2012/12/12/php-warning-missing-argument-2-for-wpdb-prepare/) but am having trouble changing this code so that it is correct and not throwing the error. Can anyone help me with this?

    Thanks!

    Reply
    • Pippin says:
      December 13, 2012 at 7:11 pm

      I’ve updated the code to fix the error.

    • Melinda says:
      December 13, 2012 at 7:55 pm

      That works again. Thank you so much for your help!

  8. Name says:
    December 17, 2012 at 5:21 pm

    ty for update!

    Reply
    • Name says:
      December 17, 2012 at 5:32 pm

      Take it back, nothing has changed? Same 3.5 update problem

  9. Name says:
    December 17, 2012 at 5:38 pm

    okay, jk it works. maybe put your example function in one block so it doesn’t look so janky? Thanks for this btw.

    Reply
    • Pippin says:
      December 17, 2012 at 6:36 pm

      Whoops, fixed!

  10. Eric Daams says:
    February 14, 2013 at 12:31 am

    Hi Pippin,

    Great tip. Using this to get the attachment ID of a logo uploaded via the WP customizer.

    One quick question: Is there a reason why you use $wpdb->prefix instead of just using $wpdb->posts inside the SQL? Since it’s a default table should $wpdb->posts always have the correct prefix anyway?

    Cheers,
    Eric

    Reply
    • Pippin says:
      February 14, 2013 at 3:27 pm

      Nope, no reason :)

Leave a Reply Cancel reply

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

You may 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>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • User Submitted Image Gallery – Final Overview
  • User Submitted Image Gallery – Part 8
  • User Submitted Image Gallery – Part 7
  • User Submitted Image Gallery – Part 6
  • Adding a Simple Image Gallery with the Repeatable Upload Field

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • @mgibbs189 I think that will work
    May 21, 2013
  • @mgibbs189 register the script on wp_enqueue_scripts then use wp_print_script() on the wp_print_scripts action
    May 21, 2013
  • @mgibbs189 So you need the action to run right after your script is enqueued?
    May 21, 2013

Topics

campaign monitor shortcodes Rémi Corson add_options_page the_content Sugar Event Calendar featured get_user_meta contextual help add_shortcode attachments Tom McFarlin wp_enqueue_script short codes mail chimp authors Related posts attachment plugin image login forms do_action recent posts post types bbpress apply_filters comments short code taxonomies custom post type images Ajax gallery Stripe taxonomy jquery widgets users add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins