Skip to content

Instantly share code, notes, and snippets.

@asadowski10
Last active June 26, 2017 11:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asadowski10/496068291ec5ca5f3016 to your computer and use it in GitHub Desktop.
Save asadowski10/496068291ec5ca5f3016 to your computer and use it in GitHub Desktop.
<?php
/**
* Function copied from http://frankiejarrett.com/get-an-attachment-id-by-url-in-wordpress/
* Return an ID of an attachment by searching the database with the file URL.
*
* First checks to see if the $url is pointing to a file that exists in
* the wp-content directory. If so, then we search the database for a
* partial match consisting of the remaining path AFTER the wp-content
* directory. Finally, if a match is found the attachment ID will be
* returned.
*
* @return {int} $attachment
*/
private static function fjarrett_get_attachment_id_by_url( $url ) {
// Split the $url into two parts with the wp-content directory as the separator.
$parse_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->posts WHERE post_type = 'attachment' AND guid LIKE %s", $parsed_url[1] ) );
if ( is_array( $attachment ) && ! empty( $attachment ) ) {
return array_shift( $attachment );
}
return null;
}
@asadowski10
Copy link
Author

Improve performance on query. Check only post_type attachment ;)

@andreilupu
Copy link

Why not use attachment_url_to_postid ? I'm not sure if you can rely on guid anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment