From 5ae266fdc490ea8722b9effed94ddcb243646f1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Zi=C3=83=C2=B3=C3=85=E2=80=9Akowski?= Date: Tue, 19 Apr 2022 14:38:16 +0000 Subject: [PATCH] REST API: Respect _fields query arg in preloaded requests Ensures that preloaded request can include a `_fields` query param that asks that only selected response fields are returned. Props jsnajdr, timothyblynjacobs. Fixes #55213. See #55567. git-svn-id: https://develop.svn.wordpress.org/trunk@53217 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/rest-api.php | 4 ++-- tests/phpunit/tests/rest-api.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index 941aa25f12..13666c0dfc 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -2868,12 +2868,12 @@ function rest_preload_api_request( $memo, $path ) { $response = rest_do_request( $request ); if ( 200 === $response->status ) { $server = rest_get_server(); + /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ + $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $server, $request ); $embed = $request->has_param( '_embed' ) ? rest_parse_embed_param( $request['_embed'] ) : false; $data = (array) $server->response_to_data( $response, $embed ); if ( 'OPTIONS' === $method ) { - $response = rest_send_allow_header( $response, $server, $request ); - $memo[ $method ][ $path ] = array( 'body' => $data, 'headers' => $response->headers, diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php index acc0e7110c..fa25502959 100644 --- a/tests/phpunit/tests/rest-api.php +++ b/tests/phpunit/tests/rest-api.php @@ -2490,4 +2490,32 @@ class Tests_REST_API extends WP_UnitTestCase { array( '', array(), array() ), ); } + + /** + * @ticket 55213 + */ + public function test_rest_preload_api_request_fields() { + $preload_paths = array( + '/', + '/?_fields=description', + ); + + $preload_data = array_reduce( + $preload_paths, + 'rest_preload_api_request', + array() + ); + + $this->assertSame( array_keys( $preload_data ), array( '/', '/?_fields=description' ) ); + + // Unfiltered request has all fields + $this->assertArrayHasKey( 'description', $preload_data['/']['body'] ); + $this->assertArrayHasKey( 'routes', $preload_data['/']['body'] ); + + // Filtered request only has the desired fields + links + $this->assertSame( + array_keys( $preload_data['/?_fields=description']['body'] ), + array( 'description', '_links' ) + ); + } }