获取 WooCommerce 可变产品中每个活动变体的库存数量

Get the stock quantity of each active variation in WooCommerce variable products

我需要在 Woocommerce 中显示可变产品的每个变体的库存数量

我用这个代码显示库存数量:

<?php echo $product->get_stock_quantity(get_the_ID()); ?>

现在我有这个产品:

衬衫有红色,蓝色 可变产品。

"Red Shirt" has a stock quantity of 3
"Blue Shirt" has a stock quantity of 4

所以我需要展示:

Blue = 3 // Red = 4

我该怎么做?

您可以使用 get_post_meta() 函数从数据库中获取值。

产品库存数量值存储在 wp_postmeta table.

$stock = get_post_meta( $post->ID, '_stock', true );

 global $woocommerce, $product, $post;
// test if product is variable
if ($product->is_type( 'variable' )) 
{
    $available_variations = $product->get_available_variations();
    foreach ($available_variations as $key => $variation) 
    { 
$variation_id = $variation['variation_id'];
         $variation_obj = new WC_Product_variation($variation_id);
         $stock = $variation_obj->get_stock_quantity();
    }
}

您有一个可变产品,具有不同的颜色变化和库存数量。

因此您需要为每个变体获取: - 变化库存数量: - 此变体的属性 '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;
    }

}

This will exactly output something like (the color name "=" the stock quantity + separator):

Blue = 3 // Red = 4

经过测试并在 WooCommerce 3+ 中完美运行