WP_REST_Server::embed_links( array $data, bool|string[] $embed = true ): array

In this article

Embeds the links from the data into the request.

Parameters

$dataarrayrequired
Data from the request.
$embedbool|string[]optional
Whether to embed all links or a filtered list of link relations.

Default:true

Return

array Data with sub-requests embedded.
  • _links array
    Links.
  • _embedded array
    Embedded objects.

Source

protected function embed_links( $data, $embed = true ) {
	if ( empty( $data['_links'] ) ) {
		return $data;
	}

	$embedded = array();

	foreach ( $data['_links'] as $rel => $links ) {
		/*
		 * If a list of relations was specified, and the link relation
		 * is not in the list of allowed relations, don't process the link.
		 */
		if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
			continue;
		}

		$embeds = array();

		foreach ( $links as $item ) {
			// Determine if the link is embeddable.
			if ( empty( $item['embeddable'] ) ) {
				// Ensure we keep the same order.
				$embeds[] = array();
				continue;
			}

			if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
				// Run through our internal routing and serve.
				$request = WP_REST_Request::from_url( $item['href'] );
				if ( ! $request ) {
					$embeds[] = array();
					continue;
				}

				// Embedded resources get passed context=embed.
				if ( empty( $request['context'] ) ) {
					$request['context'] = 'embed';
				}

				if ( empty( $request['per_page'] ) ) {
					$matched = $this->match_request_to_handler( $request );
					if ( ! is_wp_error( $matched ) && isset( $matched[1]['args']['per_page']['maximum'] ) ) {
						$request['per_page'] = (int) $matched[1]['args']['per_page']['maximum'];
					}
				}

				$response = $this->dispatch( $request );

				/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
				$response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );

				$this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
			}

			$embeds[] = $this->embed_cache[ $item['href'] ];
		}

		// Determine if any real links were found.
		$has_links = count( array_filter( $embeds ) );

		if ( $has_links ) {
			$embedded[ $rel ] = $embeds;
		}
	}

	if ( ! empty( $embedded ) ) {
		$data['_embedded'] = $embedded;
	}

	return $data;
}

Hooks

apply_filters( ‘rest_post_dispatch’, WP_HTTP_Response $result, WP_REST_Server $server, WP_REST_Request $request )

Filters the REST API response.

Changelog

VersionDescription
5.4.0The $embed parameter can now contain a list of link relations to include.
4.4.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.