Categories
Code

Get WordPress attachment ID by URL

Pass in an (non-resized) attachment URL in WordPress and it returns the ID of the attachment. Doesn’t work with thumbnails.

function ed_get_attachment_id_by_url($url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE guid='%s';", $url));
    if ( $attachment ) {
        return $attachment[0];
    } else {
        return false;
    }
}