Search code examples
phpwoocommercestockproduct-variations

How get variation's stock quantity woocommerce


I'm developing a theme for wordpress and woocommerce and need to show a variation's stock.

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

I read 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.

Do 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 tried to get the max quantity with this:

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

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


Solution

  • Ok, with this I can take the quantity. But is not useful.

    With this I can prepare a code that make differents sentences, one for each product, and show it when a variation would be selected using jquery.

    But this is not good idea. Is not elegant. I though existed something like

    $product->get_variation_price()
    

    This code return the variation price when is selected. But

    $product->get_stock_quantity();
    

    not change when variation is selected because show me the global stock.

    Can somebody give me an elegant solution? Or not exists?

    UPDATE

    Finally I used

    $product->get_available_variations()
    

    To get the data.

    With this I've generated html code, hidden with css, and I show it when I click on variation's color.

    UPDATE December 2022

    Seems that we have a most current answer on a new comment on this post: https://stackoverflow.com/a/71503746/3877879