WC_Structured_Data::count_matching_variations
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.
Метод класса: WC_Structured_Data{}
Хуков нет.
Возвращает
int. Number of matching variations (0, 1, or 2 when more than one matches).
Использование
// private - только в коде основоного (родительского) класса $result = $this->count_matching_variations( $product, $match_attributes );
- $product(WC_Product) (обязательный)
- Variable product.
- $match_attributes(массив) (обязательный)
- Requested attributes keyed by
attribute_*name.
Код WC_Structured_Data::count_matching_variations() WC Structured Data::count matching variations WC 11.3.0
private function count_matching_variations( $product, $match_attributes ) {
$match_count = 0;
$child_ids = $product->get_children();
if ( ! empty( $child_ids ) ) {
// Prime caches to reduce future queries.
_prime_post_caches( $child_ids );
}
foreach ( $child_ids 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;
}