rest_pre_echo_responsefilter-hookWP 4.8.1

Allows you to modify REST API response data before the response is sent to the client.

This filter fires at the very end of REST request processing. It allows the final data array to be changed before it is serialized to JSON and sent to the client.

It is useful for adding, removing, or changing response fields, as well as implementing filtering or caching logic.

This is the last opportunity to change the data before it is sent to the client.

The hook is called in WP_REST_Server::serve_request() after the response data has been prepared and before it is output.

Usage

add_filter( 'rest_pre_echo_response', 'wp_kama_rest_pre_echo_response_filter', 10, 3 );

/**
 * Function for `rest_pre_echo_response` filter-hook.
 * 
 * @param array           $result  Response data to send to the client.
 * @param WP_REST_Server  $server  Server instance.
 * @param WP_REST_Request $request Request used to generate the response.
 *
 * @return array
 */
function wp_kama_rest_pre_echo_response_filter( $result, $server, $request ){

	// filter...
	return $result;
}
$result(array)
Array of response data that will be serialized and sent to the client.
$server(WP_REST_Server)
REST API server instance handling the request.
$request(WP_REST_Request)
Request object used to generate the response.

Examples

#1 Add a custom message to the response

Add an extra custom_message field to the response data.

add_filter( 'rest_pre_echo_response', function( $result, $server, $request ) {
	$result['custom_message'] = 'The data was processed successfully.';
	return $result;
}, 10, 3 );

#2 Handle errors in the response

Convert an error object into a structured array containing a code and message.

add_filter( 'rest_pre_echo_response', function( $result, $server, $request ) {
	if ( is_wp_error( $result ) ) {
		return [
			'error'   => true,
			'code'    => $result->get_error_code(),
			'message' => $result->get_error_message(),
		];
	}
	return $result;
}, 10, 3 );

#3 Cache a REST API response

Store the response data in the cache for later use.

add_filter( 'rest_pre_echo_response', function( $result, $server, $request ) {
	$cache_key = 'rest_response_' . md5( $request->get_route() . serialize( $request->get_params() ) );
	set_transient( $cache_key, $result, HOUR_IN_SECONDS );

	return $result;
}, 10, 3 );

Changelog

Since 4.8.1 Introduced.

Where the hook is called

WP_REST_Server::serve_request()
rest_pre_echo_response
wp-includes/rest-api/class-wp-rest-server.php 539
$result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );

Where the hook is used in WordPress

Usage not found.