rest_filter_response_fields

函数
rest_filter_response_fields ( $response, $server, $request )
参数
  • (WP_REST_Response) $response Current response being served.
    Required:
  • (WP_REST_Server) $server ResponseHandler instance (usually WP_REST_Server).
    Required:
  • (WP_REST_Request) $request The request that was used to make current response.
    Required:
返回值
  • (WP_REST_Response) Response to be served, trimmed down to contain a subset of fields.
定义位置
相关方法
rest_filter_response_by_contextregister_rest_fieldrest_ensure_responsesanitize_post_fieldget_oembed_response_data
引入
4.8.0
弃用
-

rest_filter_response_fields: 这个函数用于根据请求的字段过滤响应数据。它接收一个数据对象、一个要包括的字段数组和一个要排除的字段数组,并返回过滤后的数据。

过滤REST API响应,只包括白名单上的一套响应对象字段。

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

	$data = $response->get_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 hierarchy.
	$fields_as_keyed = array();
	foreach ( $fields as $field ) {
		$parts = explode( '.', $field );
		$ref   = &$fields_as_keyed;
		while ( count( $parts ) > 1 ) {
			$next = array_shift( $parts );
			if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) {
				// Skip any sub-properties if their parent prop is already marked for inclusion.
				break 2;
			}
			$ref[ $next ] = isset( $ref[ $next ] ) ? $ref[ $next ] : array();
			$ref          = &$ref[ $next ];
		}
		$last         = array_shift( $parts );
		$ref[ $last ] = true;
	}

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

	$response->set_data( $new_data );

	return $response;
}

常见问题

FAQs
查看更多 >