diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index da37f902c5..601538d8ea 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -4295,11 +4295,26 @@ function attachment_url_to_postid( $url ) { } $sql = $wpdb->prepare( - "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", + "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", $path ); - $post_id = $wpdb->get_var( $sql ); + $results = $wpdb->get_results( $sql ); + $post_id = null; + + if ( $results ) { + // Use the first available result, but prefer a case-sensitive match, if exists. + $post_id = reset( $results )->post_id; + + if ( count( $results ) > 1 ) { + foreach ( $results as $result ) { + if ( $path === $result->meta_value ) { + $post_id = $result->post_id; + break; + } + } + } + } /** * Filters an attachment id found by URL. diff --git a/tests/phpunit/tests/media.php b/tests/phpunit/tests/media.php index 26d8468bc2..9b99cf9106 100644 --- a/tests/phpunit/tests/media.php +++ b/tests/phpunit/tests/media.php @@ -1058,7 +1058,10 @@ VIDEO; $this->assertEquals( $attachment_id, attachment_url_to_postid( $image_url ) ); } - function test_attachment_url_to_postid_schemes() { + /** + * @ticket 33109 + */ + function test_attachment_url_to_postid_with_different_scheme() { $image_path = '2014/11/' . $this->img_name; $attachment_id = self::factory()->attachment->create_object( $image_path, @@ -1069,13 +1072,38 @@ VIDEO; ) ); - /** - * @ticket 33109 Testing protocols not matching - */ $image_url = 'https://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path; $this->assertEquals( $attachment_id, attachment_url_to_postid( $image_url ) ); } + /** + * @ticket 39768 + */ + function test_attachment_url_to_postid_should_be_case_sensitive() { + $image_path_lower_case = '2014/11/' . $this->img_name; + $attachment_id_lower_case = self::factory()->attachment->create_object( + $image_path_lower_case, + 0, + array( + 'post_mime_type' => 'image/jpeg', + 'post_type' => 'attachment', + ) + ); + + $image_path_upper_case = '2014/11/' . ucfirst( $this->img_name ); + $attachment_id_upper_case = self::factory()->attachment->create_object( + $image_path_upper_case, + 0, + array( + 'post_mime_type' => 'image/jpeg', + 'post_type' => 'attachment', + ) + ); + + $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path_upper_case; + $this->assertEquals( $attachment_id_upper_case, attachment_url_to_postid( $image_url ) ); + } + function test_attachment_url_to_postid_filtered() { $image_path = '2014/11/' . $this->img_name; $attachment_id = self::factory()->attachment->create_object(