How to get an attachment id from a filename

I have not been able to find a reliable solution for how to lookup the id for attachments in the media library from a filename as Wordpress does not appear to provide such a function.

Most solutions rely on searching the GUID field in various tables, however there are issues with attachments uploaded with greater than 2560px resolution. Wordpress appends '-scaled' to the filename returned by functions like get_attached_file(), but this is not reflected in the guid database column.

I'd be grateful for a generic function that returns the attachment id when given a filename.

Topic functions attachments Wordpress

Category Web


I worked this out eventually by tracing through the code for get_attached_file() to see where it was getting the filename from, and reverse engineered the following:

function get_attachment_id_by_filename($filename) {
    global $wpdb;
    $sql = $wpdb->prepare("SELECT * FROM  $wpdb->posts WHERE  post_type = 'attachment' and guid like %s order by post_date desc", "%$filename");
    $attachments = $wpdb->get_results($sql, OBJECT);
    return $attachments[0]->ID ?? false;
}

Note that it is possible the query will return more than one row if the same file basename exists in different media library folders. This routine will however only return the most recent found.

This works for everything I can throw at it so far, but welcome any issues people may be aware of with this solution.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.