Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active May 21, 2016 02:14
Show Gist options
  • Save kjbrum/73f2b37b4865ee68a981 to your computer and use it in GitHub Desktop.
Save kjbrum/73f2b37b4865ee68a981 to your computer and use it in GitHub Desktop.
Get the ID of an attachment image using the file URL. Original: https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
<?php
/**
* Get the ID of an attachment image using the file URL.
*
* @param string $url The URL of the image
* @return int $attachment The attachment image ID
*/
function wp_url_to_attachmentid( $url ) {
// Split the $url into two parts with the wp-content directory as the separator
$parsed_url = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );
// Get the host of the current site and the host of the $url, ignoring www
$this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
$file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
// Return nothing if there aren't any $url parts or if the current host and $url host do not match
if( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
return;
}
// Now we're going to quickly search the DB for any attachment GUID with a partial path match
// Example: /uploads/2013/05/test-image.jpg
global $wpdb;
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );
// Returns null if no attachment is found
return $attachment[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment