Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active February 25, 2022 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vincentorback/0c1ef8a5fda2addca846e7983a361bdf to your computer and use it in GitHub Desktop.
Save vincentorback/0c1ef8a5fda2addca846e7983a361bdf to your computer and use it in GitHub Desktop.
Get the attachment ID for a given file url in WordPress
<?php
if ( ! function_exists( 'get_attachment_id_from_url' ) ) {
/**
* Get the attachment ID for a given file url
*
* @link http://wordpress.stackexchange.com/a/7094
* @param string $url
* @return boolean|integer
*/
function get_attachment_id_from_url ($url) {
$dir = wp_upload_dir();
if (false === strpos($url, $dir['baseurl'] . '/')) {
return false;
}
$file = basename( $url );
$query = array(
'post_type' => 'attachment',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => $file,
'compare' => 'LIKE'
)
)
);
$ids = get_posts( $query );
if (!empty($ids)) {
foreach ($ids as $id) {
if (wp_get_attachment_url($id) === $url) {
return $id;
}
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment