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 = '';

// 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= '';
$thumb_id= attachment_url_to_postid($image_src);
echo $thumb_id;

Hope this help.


How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

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.

Related Posts