From a6aa1a07541db92dfec7a88c2da756211ff4195f Mon Sep 17 00:00:00 2001 From: Ryan McCue Date: Tue, 17 Nov 2015 04:11:21 +0000 Subject: [PATCH] REST API: Optimise for singular error instances. Previously, the API returned a list of errors, as WP_Error can hold multiple error codes internally. This isn't a particularly common use case, and it makes handling errors on the client side more complex than it needs to be. Fixes #34551. git-svn-id: https://develop.svn.wordpress.org/trunk@35653 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/rest-api/class-wp-rest-server.php | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php index 05e10a9399..b094634985 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -162,14 +162,21 @@ class WP_REST_Server { $status = 500; } - $data = array(); + $errors = array(); foreach ( (array) $error->errors as $code => $messages ) { foreach ( (array) $messages as $message ) { - $data[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) ); + $errors[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) ); } } + $data = $errors[0]; + if ( count( $errors ) > 1 ) { + // Remove the primary error. + array_shift( $errors ); + $data['additional_errors'] = $errors; + } + $response = new WP_REST_Response( $data, $status ); return $response; @@ -198,7 +205,7 @@ class WP_REST_Server { $error = compact( 'code', 'message' ); - return wp_json_encode( array( $error ) ); + return wp_json_encode( $error ); } /**