Php – How get variation’s stock quantity woocommerce

phpstockvariationswoocommerce

I'm developing a theme for wordpress and woocommerce.

I need show variation's stock.

<p class="stock-m13"><?php echo $product->get_stock_quantity(); ?></p>

(here: How to get the stock quantity of an article from woocommerce?) but this code only show me the global stock quantity, not each variation quantity.

I need another function to get variation quantity?
Or it is possible that my code is not completed (I think it because I have used Twenty Fifteen theme and variation quantity is showed)?

I try to get max quantity with this:

<?php
    foreach ($product->get_available_variations() as $key) {
        echo $key['max_qty'] .'<br/>';
    }
?>

And I get it, but I don't know if this is useful when the stock goes down.

Best Solution

Given a variable product with multiple variations in order to get each variation stock quantity:

function get_stock_variations_from_product(){
    global $product;
    $variations = $product->get_available_variations();
    foreach($variations as $variation){
         $variation_id = $variation['variation_id'];
         $variation_obj = new WC_Product_variation($variation_id);
         $stock = $variation_obj->get_stock_quantity();
    }
}

This is the cleanest way I figured out for WC 2.5, I think there might be better ways in terms of performance but not as clean.

Related Question