Massively improved function developed for plugin heavy on images:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | if ( ! function_exists( 'get_attachment_id' ) ) { /** * Get the Attachment ID for a given image URL. * * @link http://wordpress.stackexchange.com/a/7094 * * @param string $url * * @return boolean|integer */ function get_attachment_id( $url ) { $dir = wp_upload_dir(); // baseurl never has a trailing slash if ( false === strpos( $url, $dir['baseurl'] . '/' ) ) { // URL points to a place outside of upload directory return false; } $file = basename( $url ); $query = array( 'post_type' => 'attachment', 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_wp_attached_file', 'value' => $file, 'compare' => 'LIKE', ), ) ); // query attachments $ids = get_posts( $query ); if ( ! empty( $ids ) ) { foreach ( $ids as $id ) { // first entry of returned array is the URL if ( $url === array_shift( wp_get_attachment_image_src( $id, 'full' ) ) ) return $id; } } $query['meta_query'][0]['key'] = '_wp_attachment_metadata'; // query attachments again $ids = get_posts( $query ); if ( empty( $ids) ) return false; foreach ( $ids as $id ) { $meta = wp_get_attachment_metadata( $id ); foreach ( $meta['sizes'] as $size => $values ) { if ( $values['file'] === $file && $url === array_shift( wp_get_attachment_image_src( $id, $size ) ) ) return $id; } } return false; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.