Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to show stock quantities of each variations of a variable product in Woocommerce

I use this code to show stock quantity:

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

Now I have this product:

Shirt has Red , Blue for variable product.

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

so I need to show:

Blue = 3 // Red = 4

How can I do it?

like image 538
Alireza Darvishi Avatar asked Dec 24 '22 15:12

Alireza Darvishi


2 Answers

You have a variable products with different color variations and stock quantity by variation.

So you need to get for each variation: - the variation stock quantity: - the attribute 'pa_color' term name for this variation

Assuming that you already get the WC_Product_Variable object $product, here is the code:

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

Tested and perfectly works in WooCommerce 3+

like image 51
LoicTheAztec Avatar answered May 02 '23 21:05

LoicTheAztec


 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();
    }
}
like image 20
Parth Trivedi Avatar answered May 02 '23 21:05

Parth Trivedi