I have the URL of an image which I know is an attachment. Now, I need to find out the attachment ID.

This is what I’ve got (thanks to PippinsPlugins):

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

This works fine for an URL like this:
http://example.com/wp-content/uploads/2015/03/picture.png

My problem is, the URL is the URL of a cropped picture, so it is
http://example.com/wp-content/uploads/2015/03/picture-300×297.png

My next problem is right now, I can’t simply explode the URL to remove 300×297, since I might have pictures, which are not cropped but might have a file name like 'picture2-dontexplodeme.png'

Basically, I need a fool proof solution haha. If there is anyone out there, who has an easy solution, I would be very happy 🙂

1 Answer
1

function get_attachment_id_from_src ($image_src) {

    global $wpdb;
    $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
    $id = $wpdb->get_var($query);
    return $id;

}

Leave a Reply

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