WordPress.org

Make WordPress Core


Ignore:
Timestamp:
05/02/2018 01:24:30 AM (3 years ago)
Author:
pento
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php

    r42356 r43087  
    200200    public function prepare_item_for_response( $status, $request ) {
    201201
    202         $data = array(
    203             'name'         => $status->label,
    204             'private'      => (bool) $status->private,
    205             'protected'    => (bool) $status->protected,
    206             'public'       => (bool) $status->public,
    207             'queryable'    => (bool) $status->publicly_queryable,
    208             'show_in_list' => (bool) $status->show_in_admin_all_list,
    209             'slug'         => $status->name,
    210         );
     202        $fields = $this->get_fields_for_response( $request );
     203        $data   = array();
     204
     205        if ( in_array( 'name', $fields, true ) ) {
     206            $data['name'] = $status->label;
     207        }
     208
     209        if ( in_array( 'private', $fields, true ) ) {
     210            $data['private'] = (bool) $status->private;
     211        }
     212
     213        if ( in_array( 'protected', $fields, true ) ) {
     214            $data['protected'] = (bool) $status->protected;
     215        }
     216
     217        if ( in_array( 'public', $fields, true ) ) {
     218            $data['public'] = (bool) $status->public;
     219        }
     220
     221        if ( in_array( 'queryable', $fields, true ) ) {
     222            $data['queryable'] = (bool) $status->publicly_queryable;
     223        }
     224
     225        if ( in_array( 'show_in_list', $fields, true ) ) {
     226            $data['show_in_list'] = (bool) $status->show_in_admin_all_list;
     227        }
     228
     229        if ( in_array( 'slug', $fields, true ) ) {
     230            $data['slug'] = $status->name;
     231        }
    211232
    212233        $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
Note: See TracChangeset for help on using the changeset viewer.