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.

    • Ollie

      I’m about to do something similar. There are a couple of potential issues I can see, but I still think your approach is the most elegant solution available.

      1) Performance may become an issue with big databases. The guid column isn’t indexed – so even a straight WHERE condition will cause a performance hit. But a LIKE match is going to be a bigger hit.

      One thing which can be done to cut down the result set for that LIKE match is to also specify post_type = ‘attachment’ in the WHERE conditions. That column is indexed, so it’ll definitely help performance on sites with lots of posts.

      2) I’d be interested to see whether this will be affected by a change in the option in WP’s Settings > Media panel to “Organize my uploads into month- and year-based folders”. It probably won’t have any effect at all, since I don’t think WordPress will move existing files or change existing GUIDs. But it’s worth testing.

  2. Garet

    Great tips. If you were working with multiple images in a gallery how would you rewrite this? I am trying to make this work with https://en-ca.wordpress.org/plugins/fullscreen-galleria/ with the button shortcode. So include= has multiple image ids. ex. [fsg_link class=”btn” include=”112,113,114,115″]View[/fsg_link] and not having much luck.

    • Garet

      I found a solution. Here is what I did.

      “”

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

      “”

      and then in my template

      “”

      ID, ‘_listing_gallery’, true) != ”) { ?>

      ID, ‘_listing_gallery’, true);
      $doc = new DOMDocument;
      $doc->loadHTML($image_url);
      $galleryimg = $doc->getElementsByTagName(‘img’);

      $images = array();

      foreach ($galleryimg as $galleryimg){

      $galleryimg = $galleryimg->getAttribute(‘src’);
      $image_id = pippin_get_image_id($galleryimg);
      array_push($images, $image_id);
      $string = rtrim(implode(‘,’, $images), ‘,’);

      }

      echo do_shortcode(‘[fsg_link class=”btn-primary” include=”‘ . $string . ‘”]View Full Screen[/fsg_link]’);

      ?>

      “”

      Worked like a charm.

  3. Danny Cooper

    Thanks Pippin!

    • Bear Function

      Storm,

      That’s not quite right. The url_to_postid function doesn’t do what Pippin’s function does. It only works for URLs in the format “example.com/?attachment_id=N”.

      In fact the article you linked to has a link back to this post for situations where you need to get the id from a full URL.

  4. Yasir

    Thanks ?

  5. Adam

    I’d retire this post if possible as its always best to use official WP functions if they exist and they have for a few years to do the task at hand here. attachment_url_to_postid()

  6. Azaman Dias

    Is it possible to get the file ID from it’s path, NOT the URL?
    As it does not work if there are special/non-unicode symbols in the file name and the PATH parses OK?

  7. Nobir

    You don’t need to create function for the cause WP already has those type function

    for Attachment url to Attachment id … use

    attachment_url_to_postid( string $url );

    and for any url to Post ID … use

    url_to_postid( string $url )

    • Nobir

      for the ID*
      type of function*

      my my I just mistake sorry for that 😀

  8. falcon

    `function attachment_url_to_postid( string $url ) ` is OK.

  9. Patel Krunal

    i always looking to learn something new from your site. thank you for this article.

Comments are closed.