How get variation's stock quantity woocommerce

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.


Yes, your way is the correct way to grab a variation's stock.

As long as you are getting the variations fresh from the database every time you need to use its stock quantity then you should be okay with using this method.

*******UPDATEED

I'm not sure I understand what you're trying to do. You should just be able to grab both variation stock and send them over to jquery to play with.

$product_variable = new WC_Product_Variable($product->id);
$product_variations = $product_variable->get_available_variations();

foreach ($product_variations as $variation)  {
  $stock[$variation['attribute_pa_variation-name']] = $variation['max_qty'];
}

Here I'm assigning stock level to an associative array with attribute_pa_"your-attribute-name" as the key

Now I can send my array over to jQuery.

Please clarify if I'm mis-understanding the question.


The below code will print all attributes with 'is_in_stock' variable.

<?php
    global $product;
    $product_variations = $product->get_available_variations();

    foreach ($product_variations as $variation)  {
        $var_data = $variation['attributes'];
        $var_data['in_stock'] = $variation['is_in_stock'];
    }

    //List all attributes with stock available or not array..
    echo '<pre>';
    print_r($var_data);
    echo '</pre>';
    die;
?>