## functions – How to get an attachment id from a filename

Question

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;
$attachments =$wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value like'%$filename'", OBJECT);
return \$attachments[0]->post_id ?? false;
}


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

0
9 months 2022-04-26T00:29:10-05:00 0 Answers 0 views 0