Skip to content

Instantly share code, notes, and snippets.

@ollietreend
Created September 4, 2017 17:03
Show Gist options
  • Save ollietreend/01d792630b825643ec9addf503faf6e2 to your computer and use it in GitHub Desktop.
Save ollietreend/01d792630b825643ec9addf503faf6e2 to your computer and use it in GitHub Desktop.
Get a WordPress attachment ID given its URL
<?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