Make WordPress Core

Changeset 54127


Ignore:
Timestamp:
09/11/2022 10:00:16 PM (2 years ago)
Author:
kadamwhite
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/class-wp-rest-server.php

    r54083 r54127  
    232232
    233233    /**
     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
     260    /**
    234261     * Handles serving a REST API request.
    235262     *
     
    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();
     
    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
Note: See TracChangeset for help on using the changeset viewer.