我希望将产品更改为特定的KEY / VALUE属性,如下所示:
变化1 :键属性“颜色”值属性“蓝色” |键属性“大小”值属性“ XS”
版本2 :键属性“颜色”值属性“黄色” |键属性“大小”值属性“ X”
我想获得 Variation 2 ,我该如何实现?
答案 0 :(得分:0)
尝试以下注释代码:
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_Product
和WC_Product_Variarion
方法上使用它。
以类似的方式完成