REST API: Filter responses based on the _fields parameter, before data is processed.

Historically, the REST API would generate the entire response object, including running expensive filters, then it would apply the `_fields` parameter, discarding the fields that weren't specificed.

This change causes `_fields` to be applied earlier, so that only requested fields are processed.

Props danielbachhuber.
See #43874.



git-svn-id: https://develop.svn.wordpress.org/trunk@43087 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Gary Pendergast
2018-05-02 01:24:30 +00:00
parent 1a4e28818f
commit 4ac3f4c13a
22 changed files with 526 additions and 167 deletions
@@ -691,42 +691,42 @@ class WP_REST_Terms_Controller extends WP_REST_Controller {
*/
public function prepare_item_for_response( $item, $request ) {
$schema = $this->get_item_schema();
$fields = $this->get_fields_for_response( $request );
$data = array();
if ( ! empty( $schema['properties']['id'] ) ) {
if ( in_array( 'id', $fields, true ) ) {
$data['id'] = (int) $item->term_id;
}
if ( ! empty( $schema['properties']['count'] ) ) {
if ( in_array( 'count', $fields, true ) ) {
$data['count'] = (int) $item->count;
}
if ( ! empty( $schema['properties']['description'] ) ) {
if ( in_array( 'description', $fields, true ) ) {
$data['description'] = $item->description;
}
if ( ! empty( $schema['properties']['link'] ) ) {
if ( in_array( 'link', $fields, true ) ) {
$data['link'] = get_term_link( $item );
}
if ( ! empty( $schema['properties']['name'] ) ) {
if ( in_array( 'name', $fields, true ) ) {
$data['name'] = $item->name;
}
if ( ! empty( $schema['properties']['slug'] ) ) {
if ( in_array( 'slug', $fields, true ) ) {
$data['slug'] = $item->slug;
}
if ( ! empty( $schema['properties']['taxonomy'] ) ) {
if ( in_array( 'taxonomy', $fields, true ) ) {
$data['taxonomy'] = $item->taxonomy;
}
if ( ! empty( $schema['properties']['parent'] ) ) {
if ( in_array( 'parent', $fields, true ) ) {
$data['parent'] = (int) $item->parent;
}
if ( ! empty( $schema['properties']['meta'] ) ) {
if ( in_array( 'meta', $fields, true ) ) {
$data['meta'] = $this->meta->get_value( $item->term_id, $request );
}