获取 Woocommerce 中特定属性键值对的变体

Get the variation for specific attributes key value pairs in Woocommerce

我想根据特定的 KEY/VALUE 属性获取产品变体,如下所示:

变体 1:键属性 "Color" 值属性 "Blue" |键属性 "Size" 值属性 "XS"
变体 2:键属性 "Color" 值属性 "Yellow" |键属性 "Size" 值属性 "X"

我想要 变体 2,我该如何实现?

尝试以下注释代码:

global $product; // The main product variation

// OR
// $product = wc_get_product( $product_id );
// OR
// $product = wc_get_product( get_the_id() );

$color_found = $size_found = false;
$variation_id = 0;

// Loop through all available variations for the variable product
foreach($product->get_available_variations() as $child ){
    foreach($child['attributes'] as $key => $value ){
        $taxonomy  = str_replace('attribute_', '', $key);
        $attr_name = get_taxonomy( $taxonomy )->labels->singular_name; // Attribute name
        $term_name = get_term_by( 'slug', $value, $taxonomy )->name; // Value name

        if( $attr_name == 'Color' && $term_name == 'Yellow' )
            $color_found = true;

        if( $attr_name == 'Size' && $term_name == 'X' )
            $size_found = true;

        if($color_found && $size_found )
            break; // we stop the loop
    }
    if($color_found && $size_found ){
        $variation_id = $child['variation_id']; // Get and set the varition ID
        break; // we stop the loop
    }
}
// Get an instance of the WC_Product_Variarion object
$variation = wc_get_product($variation_id);

// Displaying the variation ID  
echo 'Variation ID: '.$variation_id.'<br>';

您将获得相应的 WC_Product_Variarion object 实例并能够在其上使用所有 WC_ProductWC_Product_Variarion 方法。

It can also be done in a similar way using $product->get_children() method