-
-
Save wpscholar/3b00af01863c9dc562e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get an attachment ID given a URL. | |
* | |
* @param string $url | |
* | |
* @return int Attachment ID on success, 0 on failure | |
*/ | |
function get_attachment_id( $url ) { | |
$attachment_id = 0; | |
$dir = wp_upload_dir(); | |
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory? | |
$file = basename( $url ); | |
$query_args = array( | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'value' => $file, | |
'compare' => 'LIKE', | |
'key' => '_wp_attachment_metadata', | |
), | |
) | |
); | |
$query = new WP_Query( $query_args ); | |
if ( $query->have_posts() ) { | |
foreach ( $query->posts as $post_id ) { | |
$meta = wp_get_attachment_metadata( $post_id ); | |
$original_file = basename( $meta['file'] ); | |
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' ); | |
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) { | |
$attachment_id = $post_id; | |
break; | |
} | |
} | |
} | |
} | |
return $attachment_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much for this. I'm not sure if WP has changed since this post, but I thought I'd share some of my changes:
WordPress now also creates backup files. See wp_restore_image. One way to catch them is with this modification around line 35-51:
similarly / alternatively:
In my particular case, I wanted to check for everything, including pdfs. So here is a much broader (and slower) search