首页 文章

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

提问于
浏览
2

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

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

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

Now I have this product:

variable product. 衬衫有红色,蓝色

“Red Shirt”库存数量为3“Blue Shirt”,库存数量为4

所以我需要表明:

蓝色= 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;
        }
    
    }
    

    这将完全输出类似(颜色名称“=”库存数量分隔符):蓝色= 3 //红色= 4

    经过测试,完美适用于WooCommerce 3

  • 0
    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();
        }
    }
    
  • 1

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

    产品库存数量值存储在 wp_postmeta 表中 .

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

相关问题