This function queries the WordPress' posts table and searches for an item that partially matches the URL. That way we'll get to the post ID (attachment ID). We're doing a partial match because the guid column can contain a site that is different from the original URL. This is in case the site was setup on a Test Site and then moved to live site.
Usage:
[code]
$url = 'http://example.com/wp-content/uploads/2015/02/Wildlife.ogv';
echo orbisius_get_attachment_id_by_url( $url ) ;
[/code]
[code]
/**
*
* Parses the link and to prevent issues with different hosts we'll search for paths
* % /wp-content/uploads/2015/02/Wildlife.ogv
* @global obj $wpdb
* @param str $url
* @return int
*/
function orbisius_get_attachment_id_by_url( $url ) {
global $wpdb;
$path = parse_url( $url, PHP_URL_PATH ); // /wp-content/uploads/2015/02/Wildlife.ogv
$id = $wpdb->get_var( $wpdb->prepare(
"
SELECT ID
FROM $wpdb->posts
WHERE guid LIKE '%s'
LIMIT 1
",
'%' . $path
) );
return $id;
}
[/code]
Related
- https://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/
- https://wordpress.org/support/topic/need-to-get-attachment-id-by-image-url
- https://pippinsplugins.com/retrieve-attachment-id-from-image-url/