Last active
January 24, 2018 22:30
-
-
Save misfist/9c9bd0780e81d3e0e538f9e28e717aeb to your computer and use it in GitHub Desktop.
WordPress - Get Image ID from Source
This file contains hidden or 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 mixed int $attachment_id on success || false on failure | |
*/ | |
function prefix_get_attachment_id( $url ) { | |
$attachment_id = false; | |
$dir = wp_upload_dir(); | |
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { | |
$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