Ali*_*shi 3 php wordpress product variations woocommerce
我需要显示Woocommerce中可变产品的每个变体的库存定量
我使用此代码显示库存数量:
<?php echo $product->get_stock_quantity(get_the_ID()); ?>
Run Code Online (Sandbox Code Playgroud)
现在我有这个产品:
衬衫有红色,蓝色代表可变产品。
“红色衬衫”的库存数量为3
“蓝色衬衫”的库存数量为4
所以我需要证明:
蓝色= 3 //红色= 4
我该怎么做?
您有一个具有不同颜色变化和库存数量(按变化)的可变产品。
因此,您需要获取每个变体的价格:-变体库存数量:-该变体的属性'pa_color'术语名称
假设您已经获得了WC_Product_Variable对象$product,这是代码:
if ($product->is_type( 'variable' )){
// Get the available variations for the variable product
$available_variations = $product->get_available_variations();
// Initializing variables
$variations_count = count($available_variations);
$loop_count = 0;
// Iterating through each available product variation
foreach( $available_variations as $key => $values ) {
$loop_count++;
// Get the term color name
$attribute_color = $values['attributes']['attribute_pa_color'];
$wp_term = get_term_by( 'slug', $attribute_color, 'pa_color' );
$term_name = $wp_term->name; // Color name
// Get the variation quantity
$variation_obj = wc_get_product( $values['variation_id'] );
$stock_qty = $variation_obj->get_stock_quantity(); // Stock qty
// The display
$separator_string = " // ";
$separator = $variations_count < $loop_count ? $separator_string : '';
echo $term_name . ' = ' . $stock_qty . $separator;
}
}
Run Code Online (Sandbox Code Playgroud)
这将精确地输出类似(颜色名称“ =“库存数量+分隔符):
蓝色= 3 //红色= 4
经过测试,可以在WooCommerce中完美运行3+
| 归档时间: |
|
| 查看次数: |
4636 次 |
| 最近记录: |