Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Contexts

Renato Alves edited this page Feb 21, 2019 · 13 revisions

Irving can return different data from the same route using contexts. A context is additional information about the request that Irving will use to modify the data returned.

Supported contexts are

  • site - Used to return global components, such as the header and footer.
  • pagination - Used for only returning paginated results.

Site Context

The site context indicates that every top level component should be replaced. This is primarily used on first-loads to include global elements like the header and footer, but could be used to render an entirely new layout.

By hooking into wp_irving_components_route with a higher priority than our individual routes, we can write a function that automatically inserts the header, footer, and any other global element. In this example, we're inserting other components above and below the results of a specific route.

/**
 * Setup wrapper for Irving.
 *
 * @package Irving
 */

namespace Irving;

use WP_Irving\Component;

/**
 * Apply wrapper components for site contexts.
 *
 * @param  array    $response Endpoint response.
 * @param  WP_Query $query    Endpoint query.
 * @param  string   $context  Endpoint context.
 * @return array Endpoint response.
 */
function wrapper_component_handling( $response, $query, $context ) {

	// If not a `site` context, return regular response.
	if ( 'site' !== $context ) {
		return $response;
	}

	// Return wrapper components as well.
	return Component\component(
		[
			'name'     => 'site',
			'children' => [
				Component\component( 'header' ),
				$response,
				Component\component( 'footer' ),
			],
		]
	);
}
add_filter( 'wp_irving_components_route', __NAMESPACE__ . '\wrapper_component_handling', 15, 3 );
Clone this wiki locally