Automattic\WooCommerce\Blocks\BlockTypes

ProductCollection::provide_location_context_for_inner_blocks()publicWC 1.0

Provides the location context to each inner block of the product collection block. Hint: Only blocks using the 'query' context will be affected.

The sourceData structure depends on the context type as follows:

  • site: [ ]
  • order: [ 'orderId' => int ]
  • cart: [ 'productIds' => int[] ]
  • archive: [ 'taxonomy' => string, 'termId' => int ]
  • product: [ 'productId' => int ]

Method of the class: ProductCollection{}

No Hooks.

Return

Array. $context {

The block context including the product collection location context.
@type array $productCollectionLocation {
	@type string  $type        The context type. Possible values are 'site', 'order', 'cart', 'archive', 'product'.
	@type array   $sourceData  The context source data. Can be the product ID of the viewed product, the order ID of the current order viewed, etc. See structure above for more details.
}

}

Usage

$ProductCollection = new ProductCollection();
$ProductCollection->provide_location_context_for_inner_blocks( $context );
$context(array) (required)
The block context.

ProductCollection::provide_location_context_for_inner_blocks() code WC 9.4.2

public function provide_location_context_for_inner_blocks( $context ) {
	// Run only on frontend.
	// This is needed to avoid SSR renders while in editor. @see https://github.com/woocommerce/woocommerce/issues/45181.
	if ( is_admin() || \WC()->is_rest_api_request() ) {
		return $context;
	}

	// Target only product collection's inner blocks that use the 'query' context.
	if ( ! isset( $context['query'] ) || ! isset( $context['query']['isProductCollectionBlock'] ) || ! $context['query']['isProductCollectionBlock'] ) {
		return $context;
	}

	$is_in_single_product                 = isset( $context['singleProduct'] ) && ! empty( $context['postId'] );
	$context['productCollectionLocation'] = $is_in_single_product ? array(
		'type'       => 'product',
		'sourceData' => array(
			'productId' => absint( $context['postId'] ),
		),
	) : $this->get_location_context();

	return $context;
}