Skip to content

Commit bb20a18

Browse files
committed
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
1 parent 27aa1ec commit bb20a18

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/wp-includes/rest-api/class-wp-rest-server.php

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,33 @@ protected function json_error( $code, $message, $status = null ) {
230230
return wp_json_encode( $error );
231231
}
232232

233+
/**
234+
* Gets the encoding options passed to {@see wp_json_encode}.
235+
*
236+
* @since 6.1.0
237+
*
238+
* @param \WP_REST_Request $request The current request object.
239+
*
240+
* @return int The JSON encode options.
241+
*/
242+
protected function get_json_encode_options( WP_REST_Request $request ) {
243+
$options = 0;
244+
245+
if ( $request->has_param( '_pretty' ) ) {
246+
$options |= JSON_PRETTY_PRINT;
247+
}
248+
249+
/**
250+
* Filters the JSON encoding options used to send the REST API response.
251+
*
252+
* @since 6.1.0
253+
*
254+
* @param int $options JSON encoding options {@see json_encode()}.
255+
* @param WP_REST_Request $request Current request object.
256+
*/
257+
return apply_filters( 'rest_json_encode_options', $options, $request );
258+
}
259+
233260
/**
234261
* Handles serving a REST API request.
235262
*
@@ -493,7 +520,7 @@ public function serve_request( $path = null ) {
493520
return null;
494521
}
495522

496-
$result = wp_json_encode( $result );
523+
$result = wp_json_encode( $result, $this->get_json_encode_options( $request ) );
497524

498525
$json_error_message = $this->get_json_last_error();
499526

@@ -506,7 +533,7 @@ public function serve_request( $path = null ) {
506533
);
507534

508535
$result = $this->error_to_response( $json_error_obj );
509-
$result = wp_json_encode( $result->data );
536+
$result = wp_json_encode( $result->data, $this->get_json_encode_options( $request ) );
510537
}
511538

512539
if ( $jsonp_callback ) {

0 commit comments

Comments
 (0)