REST API: Don't add fields to object when not included in ?_fields=.

In [43087], we improved REST API performance by only rendering the fields specified in the request. Similarly, any fields registered with `register_rest_field()` should only be rendered when included in `?_fields=`.

Props dlh, danielbachhuber.

Merges [43736] to trunk.

Fixes #45099.

git-svn-id: https://develop.svn.wordpress.org/trunk@43986 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Jonathan Desrosiers
2018-12-12 20:50:22 +00:00
parent 140a95cf08
commit 8c85f2dfec
3 changed files with 63 additions and 2 deletions

View File

@@ -10,9 +10,23 @@
* @group restapi
*/
class WP_REST_Test_Controller extends WP_REST_Controller {
/**
* Prepares the item for the REST response.
*
* @param mixed $item WordPress representation of the item.
* @param WP_REST_Request $request Request object.
* @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
*/
public function prepare_item_for_response( $item, $request ) {
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$item = $this->add_additional_fields_to_object( $item, $request );
$item = $this->filter_response_by_context( $item, $context );
$response = rest_ensure_response( $item );
return $response;
}
/**
* Get the Post type's schema, conforming to JSON Schema
* Get the item's schema, conforming to JSON Schema.
*
* @return array
*/
@@ -72,7 +86,7 @@ class WP_REST_Test_Controller extends WP_REST_Controller {
),
);
return $schema;
return $this->add_additional_fields_schema( $schema );
}
}