Skip to content

Instantly share code, notes, and snippets.

@kingkool68
Created December 29, 2023 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingkool68/fc47514443419c72ac81122e5fff10cc to your computer and use it in GitHub Desktop.
Save kingkool68/fc47514443419c72ac81122e5fff10cc to your computer and use it in GitHub Desktop.
Get a WordPress attachment ID by it's filename. Searches '_wp_attached_file' post_meta values looking for matching filenames. If multiple are found the most recent ID by post_date is returned.
<?php
/**
* Search post attachments where the given filename matchs the attached file path
*
* @link https://wordpress.stackexchange.com/a/405142/2744
*
* @param string $filename The filename to search
*
* @return int The attachment ID of the first result sorted by post_date in reverse chronological order (most recent first)
*/
function get_attachment_id_by_filename( $filename = '' ) {
global $wpdb;
$like = '%' . $wpdb->esc_like( $filename );
$attachment_id = $wpdb->get_var(
$wpdb->prepare(
"
SELECT
post_id
FROM
`$wpdb->postmeta`
LEFT JOIN `$wpdb->posts` ON `$wpdb->postmeta`.post_id = `$wpdb->posts`.ID
WHERE
`$wpdb->postmeta`.meta_key = '_wp_attached_file'
AND `$wpdb->postmeta`.meta_value LIKE '%s'
ORDER BY
`$wpdb->posts`.post_date DESC
LIMIT 1;
",
$like
)
);
return absint( $attachment_id );
}
var_dump( get_attachment_id_by_filename( 'my-file-name.png' ) ); // Returns an ID like 123 if found or 0 if nothing is found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment