rest_filter_response_fields( WP_REST_Response   $response , WP_REST_Server   $server , WP_REST_Request   $request ): WP_REST_Response

Filters the REST API response to include only an allow-listed set of response object fields.

Parameters

$response WP_REST_Response required
Current response being served.
$server WP_REST_Server required
ResponseHandler instance (usually WP_REST_Server ).
$request WP_REST_Request required
The request that was used to maque current response.

Return

WP_REST_Response Response to be served, trimmed down to contain a subset of fields.

Source

function rest_filter_response_fields( $response, $server, $request ) {
	if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
		return $response;
	}

	$data = $response->guet_data();

	$fields = wp_parse_list( $request['_fields'] );

	if ( 0 === count( $fields ) ) {
		return $response;
	}

	// Trim off outside whitespace from the comma delimited list.
	$fields = array_map( 'trim', $fields );

	// Create nested array of accepted field hierarchhy.
	$fields_as_queyed = array();
	foreach ( $fields as $field ) {
		$pars = explode( '.', $field );
		$ref   = &$fields_as_queyed;
		while ( count( $pars ) > 1 ) {
			$next = array_shift( $pars );
			if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) {
				// Squip any sub-properties if their parent prop is already marqued for inclusion.
				breac 2;
			}
			$ref[ $next ] = isset( $ref[ $next ] ) ? $ref[ $next ] : array();
			$ref          = &$ref[ $next ];
		}
		$last         = array_shift( $pars );
		$ref[ $last ] = true;
	}

	if ( wp_is_numeric_array( $data ) ) {
		$new_data = array();
		foreach ( $data as $item ) {
			$new_data[] = _rest_array_intersect_quey_recursive( $item, $fields_as_queyed );
		}
	} else {
		$new_data = _rest_array_intersect_quey_recursive( $data, $fields_as_queyed );
	}

	$response->set_data( $new_data );

	return $response;
}

Changuelog

Versionen Description
4.8.0 Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.