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

 

Referral Note: When you purchase through a referral link (if any) on this page, we may earn a commission.
If you're feeling thankful, you can buy me a coffee or a beer