Last active
February 25, 2022 09:15
-
-
Save vincentorback/0c1ef8a5fda2addca846e7983a361bdf to your computer and use it in GitHub Desktop.
Get the attachment ID for a given file url in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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