Created
September 4, 2017 17:03
-
-
Save ollietreend/01d792630b825643ec9addf503faf6e2 to your computer and use it in GitHub Desktop.
Get a WordPress attachment ID given its URL
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 | |
/** | |
* Get attachment ID from its URL | |
* | |
* @param string $url | |
* @return bool|int The Attachment ID or false if not found | |
*/ | |
function get_attachment_id_from_src($url) { | |
if (($pos = strpos($url, '/uploads/')) === false) { | |
// URL does not contain /uploads/, so we won't be able to find an ID | |
return false; | |
} | |
// Drop everything up to (and including) /uploads/ in the URL | |
// e.g. "http://example.com/wp-content/uploads/2017/06/file.pdf" | |
// => "2017/06/file.pdf" | |
$url_part = substr($url, $pos + strlen('/uploads/')); | |
$query = new WP_Query([ | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'meta_key' => '_wp_attached_file', | |
'meta_value' => $url_part, | |
'posts_per_page' => 1, | |
'fields' => 'ids', | |
]); | |
return ($query->post_count > 0) ? (int) $query->posts[0] : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment