Get the total stock of all variations from a variable product In Woocommerce

前端 未结 2 1955
醉梦人生
醉梦人生 2020-12-04 01:10

IN woocommerce I would like to display the total stock of all variations in a variable product. The stock of each product variation is managed at the product variation level

2条回答
  •  一个人的身影
    2020-12-04 01:29

    add_action( 'woocommerce_before_add_to_cart_button', 'get_selected_variation_stock' );
    function get_selected_variation_stock() {
        global $product;
    
        if ($product->is_type( 'variable' ))
        {
            $avail_vari = $product->get_available_variations();
            foreach ($avail_vari as $key => $value)
            {
                $vari_id = $value['variation_id'];
                $vari_colr = $value['attributes']['attribute_pa_colour'];
                $vari_obj = new WC_Product_variation($vari_id);
                $vari_stock = $vari_obj->get_stock_quantity();
    
                echo $vari_colr . ": " . $vari_stock . " ";
    
            }
        }
    

    Paste this code into function.php of your theme and hurray your work will be done.

提交回复
热议问题