diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php index f4c4cc7879..3265691f7f 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php @@ -991,14 +991,16 @@ class WP_REST_Posts_Controller extends WP_REST_Controller { } // Parent. - if ( ! empty( $schema['properties']['parent'] ) && ! empty( $request['parent'] ) ) { - $parent = get_post( (int) $request['parent'] ); - - if ( empty( $parent ) ) { - return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) ); + if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) { + if ( 0 === (int) $request['parent'] ) { + $prepared_post->post_parent = 0; + } else { + $parent = get_post( (int) $request['parent'] ); + if ( empty( $parent ) ) { + return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) ); + } + $prepared_post->post_parent = (int) $parent->ID; } - - $prepared_post->post_parent = (int) $parent->ID; } // Menu order. diff --git a/tests/phpunit/tests/rest-api/rest-pages-controller.php b/tests/phpunit/tests/rest-api/rest-pages-controller.php index a571803d12..b74d01c716 100644 --- a/tests/phpunit/tests/rest-api/rest-pages-controller.php +++ b/tests/phpunit/tests/rest-api/rest-pages-controller.php @@ -371,6 +371,41 @@ class WP_Test_REST_Pages_Controller extends WP_Test_REST_Post_Type_Controller_Te $this->assertEquals( 0, $new_data['menu_order'] ); } + public function test_update_page_parent_non_zero() { + $page_id1 = $this->factory->post->create( array( + 'post_type' => 'page', + ) ); + $page_id2 = $this->factory->post->create( array( + 'post_type' => 'page', + ) ); + wp_set_current_user( self::$editor_id ); + $request = new WP_REST_Request( 'PUT', sprintf( '/wp/v2/pages/%d', $page_id2 ) ); + $request->set_body_params( array( + 'parent' => $page_id1, + ) ); + $response = $this->server->dispatch( $request ); + $new_data = $response->get_data(); + $this->assertEquals( $page_id1, $new_data['parent'] ); + } + + public function test_update_page_parent_zero() { + $page_id1 = $this->factory->post->create( array( + 'post_type' => 'page', + ) ); + $page_id2 = $this->factory->post->create( array( + 'post_type' => 'page', + 'post_parent' => $page_id1, + ) ); + wp_set_current_user( self::$editor_id ); + $request = new WP_REST_Request( 'PUT', sprintf( '/wp/v2/pages/%d', $page_id2 ) ); + $request->set_body_params( array( + 'parent' => 0, + ) ); + $response = $this->server->dispatch( $request ); + $new_data = $response->get_data(); + $this->assertEquals( 0, $new_data['parent'] ); + } + public function test_get_page_with_password() { $page_id = $this->factory->post->create( array( 'post_type' => 'page',