diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index 5a28f4f1d4..0498e90f47 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -2520,11 +2520,8 @@ function rest_preload_api_request( $memo, $path ) { $response = rest_do_request( $request ); if ( 200 === $response->status ) { $server = rest_get_server(); - $data = (array) $response->get_data(); - $links = $server::get_compact_response_links( $response ); - if ( ! empty( $links ) ) { - $data['_links'] = $links; - } + $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 ); diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php index e4532289ff..b7d5c3699a 100644 --- a/tests/phpunit/tests/rest-api.php +++ b/tests/phpunit/tests/rest-api.php @@ -2328,4 +2328,56 @@ class Tests_REST_API extends WP_UnitTestCase { ), ); } + + /** + * @ticket 51722 + * @dataProvider data_rest_preload_api_request_embeds_links + * + * @param string $embed The embed parameter. + * @param string[] $expected The list of link relations that should be embedded. + * @param string[] $not_expected The list of link relations that should not be embedded. + */ + public function test_rest_preload_api_request_embeds_links( $embed, $expected, $not_expected ) { + wp_set_current_user( 1 ); + $post_id = self::factory()->post->create(); + self::factory()->comment->create_post_comments( $post_id ); + + $url = sprintf( '/wp/v2/posts/%d?%s', $post_id, $embed ); + $preload_paths = array( $url ); + + $preload_data = array_reduce( + $preload_paths, + 'rest_preload_api_request', + array() + ); + + $this->assertSame( array_keys( $preload_data ), $preload_paths ); + $this->assertArrayHasKey( 'body', $preload_data[ $url ] ); + $this->assertArrayHasKey( '_links', $preload_data[ $url ]['body'] ); + + if ( $expected ) { + $this->assertArrayHasKey( '_embedded', $preload_data[ $url ]['body'] ); + } else { + $this->assertArrayNotHasKey( '_embedded', $preload_data[ $url ]['body'] ); + } + + foreach ( $expected as $rel ) { + $this->assertArrayHasKey( $rel, $preload_data[ $url ]['body']['_embedded'] ); + } + + foreach ( $not_expected as $rel ) { + $this->assertArrayNotHasKey( $rel, $preload_data[ $url ]['body']['_embedded'] ); + } + } + + public function data_rest_preload_api_request_embeds_links() { + return array( + array( '_embed=wp:term,author', array( 'wp:term', 'author' ), array( 'replies' ) ), + array( '_embed[]=wp:term&_embed[]=author', array( 'wp:term', 'author' ), array( 'replies' ) ), + array( '_embed', array( 'wp:term', 'author', 'replies' ), array() ), + array( '_embed=1', array( 'wp:term', 'author', 'replies' ), array() ), + array( '_embed=true', array( 'wp:term', 'author', 'replies' ), array() ), + array( '', array(), array() ), + ); + } }