diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 48be78e6fc..00bf9db3d9 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -3269,7 +3269,11 @@ function attachment_url_to_postid( $url ) { global $wpdb; $dir = wp_upload_dir(); - $path = ltrim( $url, $dir['baseurl'] . '/' ); + $path = $url; + + if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) { + $path = substr( $path, strlen( $dir['baseurl'] . '/' ) ); + } $sql = $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s", diff --git a/tests/phpunit/tests/media.php b/tests/phpunit/tests/media.php index 506367f8b1..c22bf623fc 100644 --- a/tests/phpunit/tests/media.php +++ b/tests/phpunit/tests/media.php @@ -443,4 +443,28 @@ VIDEO; $this->assertTrue( has_image_size( 'test-size' ) ); } + /** + * @ticket 30346 + */ + function test_attachment_url_to_postid() { + $image_path = '2014/11/' . $this->img_name; + $attachment_id = $this->factory->attachment->create_object( $image_path, 0, array( + 'post_mime_type' => 'image/jpeg', + 'post_type' => 'attachment', + ) ); + + $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/' . $image_path; + $this->assertEquals( $attachment_id, attachment_url_to_postid( $image_url ) ); + + add_filter( 'upload_dir', array( $this, '_upload_dir' ) ); + $image_url = 'http://192.168.1.20.com/wp-content/uploads/' . $image_path; + $this->assertEquals( $attachment_id, attachment_url_to_postid( $image_url ) ); + remove_filter( 'upload_dir', array( $this, '_upload_dir' ) ); + } + + function _upload_dir( $dir ) { + $dir['baseurl'] = 'http://192.168.1.20.com/wp-content/uploads'; + return $dir; + } + }