Automattic\WooCommerce\Blocks\BlockTypes\ProductCollection

HandlerRegistry::get_cart_product_idsprivateWC 1.0

Get cart product IDs from various sources. Handles loading cart products from location context or request params.

Method of the class: HandlerRegistry{}

No Hooks.

Returns

Array. The product IDs from the cart. Returns recent products for preview in editor context only.

Usage

// private - for code of main (parent) class only
$result = $this->get_cart_product_ids( $collection_args, $request );
$collection_args(array) (required)
Collection arguments with location context.
$request(WP_REST_Request|null)
Optional REST request for editor context.
Default: null

HandlerRegistry::get_cart_product_ids() code WC 10.5.0

private function get_cart_product_ids( $collection_args, $request = null ) {
	$location = $collection_args['productCollectionLocation'] ?? array();

	if ( $request ) {
		$user_id    = $request->get_param( 'userId' ) ? absint( $request->get_param( 'userId' ) ) : null;
		$user_email = $request->get_param( 'userEmail' ) ? sanitize_email( $request->get_param( 'userEmail' ) ) : null;
		if ( $user_id || $user_email ) {
			$cart_ids = CartCheckoutUtils::get_cart_product_ids_for_user( $user_id, $user_email );
			if ( ! empty( $cart_ids ) ) {
				return $cart_ids;
			}
		}
		// In editor context (REST request), show sample products for preview when cart is empty.
		$recent_product_ids = wc_get_products(
			array(
				'status'  => 'publish',
				'orderby' => 'date',
				'order'   => 'DESC',
				'limit'   => 3,
				'return'  => 'ids',
			)
		);
		return ! empty( $recent_product_ids ) ? $recent_product_ids : array();
	}

	if ( isset( $location['type'] ) && 'cart' === $location['type'] ) {
		$user_id    = isset( $location['sourceData']['userId'] ) ? absint( $location['sourceData']['userId'] ) : null;
		$user_email = isset( $location['sourceData']['userEmail'] ) ? sanitize_email( $location['sourceData']['userEmail'] ) : null;
		if ( $user_id || $user_email ) {
			return CartCheckoutUtils::get_cart_product_ids_for_user( $user_id, $user_email );
		}
	}

	// In frontend/email context, return empty array when no cart is found.
	return array();
}