diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php index 56c648e9bf..90ab5185fd 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php @@ -136,7 +136,6 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller { } $attachment = $this->prepare_item_for_database( $request ); - $attachment->file = $file; $attachment->post_mime_type = $type; $attachment->guid = $url; @@ -144,7 +143,8 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller { $attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) ); } - $id = wp_insert_post( wp_slash( (array) $attachment ), true ); + // $post_parent is inherited from $attachment['post_parent']. + $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true ); if ( is_wp_error( $id ) ) { if ( 'db_update_error' === $id->get_error_code() ) { diff --git a/tests/phpunit/tests/rest-api/rest-attachments-controller.php b/tests/phpunit/tests/rest-api/rest-attachments-controller.php index 2131e03f41..79c76a60f1 100644 --- a/tests/phpunit/tests/rest-api/rest-attachments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-attachments-controller.php @@ -773,6 +773,20 @@ class WP_Test_REST_Attachments_Controller extends WP_Test_REST_Post_Type_Control $this->assertEquals( '', $attachment['alt_text'] ); } + /** + * @ticket 40861 + */ + public function test_create_item_ensure_relative_path() { + wp_set_current_user( self::$author_id ); + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola.jpg' ); + $request->set_body( file_get_contents( $this->test_file ) ); + $response = rest_get_server()->dispatch( $request ); + $attachment = $response->get_data(); + $this->assertNotContains( ABSPATH, get_post_meta( $attachment['id'], '_wp_attached_file', true ) ); + } + public function test_update_item() { wp_set_current_user( self::$editor_id ); $attachment_id = $this->factory->attachment->create_object(