diff --git a/src/wp-includes/rest-api/class-wp-rest-response.php b/src/wp-includes/rest-api/class-wp-rest-response.php index fed1a3124d..db80029038 100644 --- a/src/wp-includes/rest-api/class-wp-rest-response.php +++ b/src/wp-includes/rest-api/class-wp-rest-response.php @@ -243,8 +243,12 @@ class WP_REST_Response extends WP_HTTP_Response { $error = new WP_Error; if ( is_array( $this->get_data() ) ) { - foreach ( $this->get_data() as $err ) { - $error->add( $err['code'], $err['message'], $err['data'] ); + $data = $this->get_data(); + $error->add( $data['code'], $data['message'], $data['data'] ); + if ( ! empty( $data['additional_errors'] ) ) { + foreach( $data['additional_errors'] as $err ) { + $error->add( $err['code'], $err['message'], $err['data'] ); + } } } else { $error->add( $this->get_status(), '', array( 'status' => $this->get_status() ) ); diff --git a/tests/phpunit/tests/rest-api/rest-server.php b/tests/phpunit/tests/rest-api/rest-server.php index 93c3a279ed..248ba56740 100644 --- a/tests/phpunit/tests/rest-api/rest-server.php +++ b/tests/phpunit/tests/rest-api/rest-server.php @@ -282,6 +282,27 @@ class Tests_REST_Server extends WP_Test_REST_TestCase { $this->assertEquals( $message, $data['message'] ); } + public function test_error_to_response_to_error() { + $code = 'wp-api-test-error'; + $message = 'Test error message for the API'; + $code2 = 'wp-api-test-error-2'; + $message2 = 'Another test message'; + $error = new WP_Error( $code, $message, array( 'status' => 400 ) ); + $error->add( $code2, $message2, array( 'status' => 403 ) ); + + $response = $this->server->error_to_response( $error ); + $this->assertInstanceOf( 'WP_REST_Response', $response ); + + $this->assertEquals( 400, $response->get_status() ); + + $error = $response->as_error(); + $this->assertInstanceOf( 'WP_Error', $error ); + $this->assertEquals( $code, $error->get_error_code() ); + $this->assertEquals( $message, $error->get_error_message() ); + $this->assertEquals( $message2, $error->errors[ $code2 ][0] ); + $this->assertEquals( array( 'status' => 403 ), $error->error_data[ $code2 ] ); + } + public function test_rest_error() { $data = array( 'code' => 'wp-api-test-error',