Get Attachment (Image) ID by Image URL- WordPress Codex

Get Attachment (Image) ID by Image URL- WordPress Codex

Being a developer, some I need to perform a special task. So I research on that topic and found a new function or ways to complete my need. Recently I worked on a client site, where I have to get the attachment ID from its URL. On research, I found two ways to resolve this.

On research, I found two ways to resolve this.

  • Fetch ID from Database, using $wpdb and
  • Using WordPress Function

#1 Fetch ID from Database

Add below function to functions.php

// retrieves the attachment ID from the file URL
function ds_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]; 
}

Now you have to call this function using image source as a parameter.

// 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 = ds_get_image_id($image_url);

// print the id
echo $image_id;

That’s it.

#2 Using WordPress function ‘attachment_url_to_postid’

This is a simple way to get attachment ID using Image source URL. Just use this.

$image_src= 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';
$thumb_id= attachment_url_to_postid($image_src);
echo $thumb_id;

Hope this help.

Enjoy!

Subscribe to this blog to get latest post direct into your inbox.

Share the Article

About author
Darshan Saroya

Darshan Saroya

A passionate WordPress Theme Developer. I love to create clean and modern themes, using the power of WordPress. Here I provide the tutorials related to WordPress Development, Core PHP and HTML.