WC_API_Resource::filter_response_fields()
Restrict the fields included in the response if the request specified certain only certain fields should be returned
Method of the class: WC_API_Resource{}
No Hooks.
Return
Array
. response data
Usage
$WC_API_Resource = new WC_API_Resource(); $WC_API_Resource->filter_response_fields( $data, $resource, $fields );
- $data(array) (required)
- the response data
- $resource(object) (required)
- the object that provided the response data, e.g. WC_Coupon or WC_Order
- $fields (required)
- -
Changelog
Since 2.1 | Introduced. |
WC_API_Resource::filter_response_fields() WC API Resource::filter response fields code WC 8.6.1
public function filter_response_fields( $data, $resource, $fields ) { if ( ! is_array( $data ) || empty( $fields ) ) { return $data; } $fields = explode( ',', $fields ); $sub_fields = array(); // get sub fields foreach ( $fields as $field ) { if ( false !== strpos( $field, '.' ) ) { list( $name, $value ) = explode( '.', $field ); $sub_fields[ $name ] = $value; } } // iterate through top-level fields foreach ( $data as $data_field => $data_value ) { // if a field has sub-fields and the top-level field has sub-fields to filter if ( is_array( $data_value ) && in_array( $data_field, array_keys( $sub_fields ) ) ) { // iterate through each sub-field foreach ( $data_value as $sub_field => $sub_field_value ) { // remove non-matching sub-fields if ( ! in_array( $sub_field, $sub_fields ) ) { unset( $data[ $data_field ][ $sub_field ] ); } } } else { // remove non-matching top-level fields if ( ! in_array( $data_field, $fields ) ) { unset( $data[ $data_field ] ); } } } return $data; }