From bb20a18040c7dddbf224bfef741592b709d64de8 Mon Sep 17 00:00:00 2001 From: "K. Adam White" Date: Sun, 11 Sep 2022 22:00:16 +0000 Subject: [PATCH] REST API: Introduce _pretty query parameter to opt in to JSON_PRETTY_PRINT. Add support for a "_pretty" meta-parameter on all REST controllers which instructs WordPress to return pretty-printed JSON, for better readability when inspecting endpoint responses in curl output or certain developer tools. Introduce the "rest_json_encode_options" filter to permit site owners to control this behavior globally. Props Viper007Bond, TimothyBlynJacobs, chrisguitarguy, johnbillion, swissspidy, adamsilverstein, danielbachhuber, rmccue. Fixes #41998. git-svn-id: https://develop.svn.wordpress.org/trunk@54127 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/class-wp-rest-server.php | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 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 4e26611bb4..ede83bdb19 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -230,6 +230,33 @@ class WP_REST_Server { return wp_json_encode( $error ); } + /** + * Gets the encoding options passed to {@see wp_json_encode}. + * + * @since 6.1.0 + * + * @param \WP_REST_Request $request The current request object. + * + * @return int The JSON encode options. + */ + protected function get_json_encode_options( WP_REST_Request $request ) { + $options = 0; + + if ( $request->has_param( '_pretty' ) ) { + $options |= JSON_PRETTY_PRINT; + } + + /** + * Filters the JSON encoding options used to send the REST API response. + * + * @since 6.1.0 + * + * @param int $options JSON encoding options {@see json_encode()}. + * @param WP_REST_Request $request Current request object. + */ + return apply_filters( 'rest_json_encode_options', $options, $request ); + } + /** * Handles serving a REST API request. * @@ -493,7 +520,7 @@ class WP_REST_Server { return null; } - $result = wp_json_encode( $result ); + $result = wp_json_encode( $result, $this->get_json_encode_options( $request ) ); $json_error_message = $this->get_json_last_error(); @@ -506,7 +533,7 @@ class WP_REST_Server { ); $result = $this->error_to_response( $json_error_obj ); - $result = wp_json_encode( $result->data ); + $result = wp_json_encode( $result->data, $this->get_json_encode_options( $request ) ); } if ( $jsonp_callback ) {