Automattic\WooCommerce\Blocks\SharedStores

ProductsStore::load_purchasable_child_productspublic staticWC 1.0

Load all purchasable child products of a parent product into state.

Method of the class: ProductsStore{}

No Hooks.

Returns

Array. The purchasable child products keyed by ID.

Usage

$result = ProductsStore::load_purchasable_child_products( $consent_statement, $parent_id ): array;
$consent_statement(string) (required)
The consent statement string.
$parent_id(int) (required)
The parent product ID.

ProductsStore::load_purchasable_child_products() code WC 10.8.1

public static function load_purchasable_child_products( string $consent_statement, int $parent_id ): array {
	self::check_consent( $consent_statement );

	// Get the parent product to retrieve child IDs.
	$parent_product = wc_get_product( $parent_id );
	if ( ! $parent_product ) {
		return array();
	}

	// Get child product IDs (for grouped products, these are linked products).
	$child_ids = $parent_product->get_children();
	if ( empty( $child_ids ) ) {
		return array();
	}

	// Query child products using include[] filter.
	// The parent[] filter doesn't work for grouped products because
	// their children are standalone products, not variations.
	$include_params = array_map(
		fn( $id ) => 'include[]=' . $id,
		$child_ids
	);
	$query_string   = implode( '&', $include_params );

	$response = Package::container()->get( Hydration::class )->get_rest_api_response_data( '/wc/store/v1/products?' . $query_string );

	if ( empty( $response['body'] ) ) {
		return array();
	}

	// Filter to only purchasable products.
	$purchasable_products = array_filter(
		$response['body'],
		fn( $product ) => $product['is_purchasable']
	);

	// Re-key array by product ID and merge into state.
	// Use array_replace instead of array_merge to preserve numeric keys.
	$keyed_products = array_column( $purchasable_products, null, 'id' );
	self::$products = array_replace( self::$products, $keyed_products );
	self::register_getters();
	wp_interactivity_state(
		self::$store_namespace,
		array( 'products' => $keyed_products )
	);

	return $keyed_products;
}