Finds the image id given the source. Or returns false.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function get_attachment_id_from_src( $attachment_url = '' ) { global $wpdb; $attachment_id = false; // If there is no url, return. if ( '' == $attachment_url ) return $attachment_id; $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$attachment_url'"; if($wpdb->get_var($query)){ $attachment_id = $wpdb->get_var($query); }else{ // If this is the URL of an auto-generated thumbnail, get the URL of the original image $attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url ); //then run the query again $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$attachment_url'"; if($wpdb->get_var($query)){ $attachment_id = $wpdb->get_var($query); } } return $attachment_id; } |