WC_Structured_Data::count_matching_variationsprivateWC 1.0

Count how many of a variable product's variations match the given attribute selection.

Mirrors the matching rules of find_matching_product_variation() (an empty stored attribute value means the variation accepts any value), but counts every match so callers can detect an ambiguous selection. Short-circuits once a second match is found.

Method of the class: WC_Structured_Data{}

No Hooks.

Returns

int. Number of matching variations (0, 1, or 2 when more than one matches).

Usage

// private - for code of main (parent) class only
$result = $this->count_matching_variations( $product, $match_attributes );
$product(WC_Product) (required)
Variable product.
$match_attributes(array) (required)
Requested attributes keyed by attribute_* name.

WC_Structured_Data::count_matching_variations() code WC 11.0.1

private function count_matching_variations( $product, $match_attributes ) {
	$match_count = 0;

	foreach ( $product->get_children() as $variation_id ) {
		$variation = wc_get_product( $variation_id );

		if ( ! $variation instanceof WC_Product_Variation ) {
			continue;
		}

		// `find_matching_product_variation()` only queries published variations, so private
		// siblings must be ignored here to keep the count consistent with the resolved variation.
		if ( ProductStatus::PUBLISH !== $variation->get_status() ) {
			continue;
		}

		$matches = true;

		foreach ( $variation->get_variation_attributes() as $attribute_key => $attribute_value ) {
			// An empty stored value means the variation accepts any value for this attribute.
			if ( '' === $attribute_value ) {
				continue;
			}
			if ( ! isset( $match_attributes[ $attribute_key ] ) || $match_attributes[ $attribute_key ] !== $attribute_value ) {
				$matches = false;
				break;
			}
		}

		if ( $matches && ++$match_count > 1 ) {
			return $match_count;
		}
	}

	return $match_count;
}