WooCommerce: Display Variations’ Stock @ Shop Page

Thanks to the various requests I get from Business Bloomer fans, this week I’m going to show you a simple PHP snippet to echo the variations’ name and stock quantity on the shop, categories and loop pages.

Of course, if “Manage stock” is not enabled at variation level, the quantity will be null, and therefore the returned string will just say “In stock” or “Out of stock”.

Enjoy!

Show the stock status of each variation for variable products on the WooCommerce Shop page

PHP Snippet: Display Variations’ Name & Stock @ WooCommerce Loop Pages

/**
 * @snippet       Display Variations' Stock @ WooCommerce Shop
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */
 
add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_echo_stock_variations_loop' );
   
function bbloomer_echo_stock_variations_loop(){
    global $product;
    if ( $product->get_type() == 'variable' ) {
        foreach ( $product->get_available_variations() as $key ) {
            $variation = wc_get_product( $key['variation_id'] );
            $stock = $variation->get_availability();
            $stock_string = $stock['availability'] ? $stock['availability'] : __( 'In stock', 'woocommerce' );
            $attr_string = array();
            foreach ( $key['attributes'] as $attr_name => $attr_value ) {
                $attr_string[] = $attr_value;
            }
            echo '<br/>' . implode( ', ', $attr_string ) . ': ' . $stock_string;
        }
    }
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
    In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce Visual Hook Guide: Archive / Shop / Cat Pages
    I’ve created a visual HTML hook guide for the WooCommerce Archive Page (which is the same page for the Shop, Category, Tag pages). This visual guide belongs to my “Visual Hook Guide Series“, that I’ve put together so that you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can […]
  • WooCommerce: Hide Prices on the Shop & Category Pages
    Interesting WooCommerce customization here. A client of mine asked me to hide/remove prices from the shop page and category pages as she wanted to drive more customers to the single product pages (i.e. increasing the click-through rate). As usual, a simple PHP snippet does the trick. I never recommend to use CSS to “hide” prices, […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

77 thoughts on “WooCommerce: Display Variations’ Stock @ Shop Page

  1. kindly if i would like to show this inside the product single page. let’s say on the product description area.

    how we can do it ?

    1. Hello Fadi, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. Hello, Rodolfo! Thank you for the fantastic snippet! I would like to ask if it is possible to make the variants appear according to their order defined in the administration (via “menu_order”). Because if I add the snippet to the product detail, the variants are sorted from largest size to smallest, while attribute swatches show the sizes according to the defined order. So, the question is whether I can select the menu_order given attributes in this snippet and sort them before displaying them. Thank you!

    1. Hello Anthony, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  3. Very nice, but it echos the slugs instead of the names?

      1. So a little bit late reply, but still stands. That code gives me the variation slug and not the name. Note that I’m using WPML, so not sure if that is the issue?
        So lets say the variation term name is “test 123”, the slug is “test-123” and it shows: test-123 in stock on default language page and test-123-en in stock on the english translated page. So it’s definitely the slug ๐Ÿ™‚
        Any input on this would be great, I can also e-mail screen if you want.
        Thanks

      2. Solved it with some extra code, can’t post here only got a blocked error. If you want, send me a email and I share it with you.

        1. Sure, feel free to email me at info@businessbloomer.com. Thank you!

  4. Hi
    I am using Woocommerce, Elementor, YITH Woocommerce Badge and Astra Theme
    but the badge will not show on the grid side, only on the single product page
    How to fix it

    Best Regards
    From App Web
    Denmark

    1. Hi there, this definitely works with default WooCommerce, so you’ll need to identify the custom hook that is used by either one of those plugins/themes and change the code accordingly

  5. Hy,
    oh very nice Work ๐Ÿ˜‰

    could you assign a css class to a variation that is not in stock?
    assign a css class?

    Thanks Henk

    1. Hey Henk, that’s possible for sure

  6. Great snippet! But there is a small bug.
    If you have selected the setting
    “Sold individually – Enable this to only allow one of this item to be bought in a single order”
    it will always return a stock value of 1

    1. Yep, you’re right. I fully revised the snippet, check it out

  7. Exactly what I was needing, thank you!

  8. Works exactly as expected!! Thanks!! I added some code to centre align the text:

     echo '<br/>' .'<div style=\'text-align: center\'>'. implode( ', ', $attr_string ) . ': ' . $key['max_qty'] . ' in stock'.'</div>'; 
  9. Hi. I tried this. Storefront theme. Woo 5.1. I just copy pasted the snippet.

    It just says I have 5 of everything. Most variations aren’t in stock and there are no more than 2 of anything. Mostly just one. Any ideas?

    1. Hi Charles that’s weird. If you wish send me your credentials and I’ll take a quick look

  10. I need this effect in the original “news” and “sale” woocommerce blocks. How can I get it?

    1. Hi Monika, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  11. Just a note that this will return ‘out of stock’ for any items that don’t use stock.

    1. Noted! Thanks

  12. Hi Rodolfo,

    I have added the PHP Snippet: Display Variationsโ€™ Name & Stock @ WooCommerce Loop Pages to my functions.php in my child theme. All the variations show up on the shop page but not on the product page even though the php shows up there.

    Also, if I allow backorders, the variation shows up as “not is stock.” This is after caches are purged.

    Here is a snippet from the product page:

    [{“attributes”:{“attribute_resistance”:”1.8\u03a9 Pack”},”availability_html”:”46 in stock/n

    Here is the CSS for the attribute on the product page:

    .p {
    margin-top: -2em;
    float: left;
    margin-left: 0px;
    margin-bottom: 6em;
    display: block;
    }

    What am I doing wrong?

    Thank you in advance.

    Greg

    1. Hi Gregory, this only works on the shop/cat pages and not on the single product. Also, it might need adjustments if you have backorders enabled

  13. Hi Rodolfo,
    Thank you very much for your contribution, how can I do to show the variations with price?

    Thank you

    Felipe

    1. Hi Felipe, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  14. Hello Dear,

    Can you please help me, i like this option to show only for admin user only

    Thanks

    1. Hi Ali, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  15. This snippet works great! April 2020 on Woocommerce 4.0.1 – WordPress 5.4 – PHP7.3.13 – Thanks so much!

    1. Great!

  16. Hey Rodolfo,
    this snippet and all of your posts are awesome.

    I have a question regarding the shown information. It shows the titel-slug instead of the titel-name of the attributes. Can you tell me how to change this?

    Cheers,
    Janos

    1. Hi Janos, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  17. Hi Rodolfo,
    In the current version of Woocommerce 3.6.5, this feature comes by default, but I want it not to be displayed.
    How to do it?
    Thanks You.

    1. Hi Mario

      In the current version of Woocommerce 3.6.5, this feature comes by default, but I want it not to be displayed.

      Honestly, I don’t think that’s possible. Can you disable all plugins and switch to another theme and see if it goes away? If it does, then it’s a custom plugin or your theme

  18. Great post, thank you!

    How can i add this to the single product page along with the “add to card” button?
    I want to show all the variations as a table and in each row i want a “add to card” button :/

    how can i do that?

    1. Hey Rafael, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  19. Your solution works fine. I have three colors (red, green, blue) and three sizes (short, mid, long). when I chose the color and size stock appears. However, if I don’t chose any or both the filters no stock is visible. How can I show sum of all the products when no filter is chosen. How can I show the green color products when green is chosen but size is left alone?

    1. Hey Zaber, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  20. Hey BB, thx a lot for your snippets, they are realy impressive and helpful.
    Iยดm just a copy and paste junky with a litle bit understanding for code.
    For my shop i use your code to bring another view for stock status with some color and font awesome icons.
    Also it is combined for variable and simple products, for me it works great with the enfold theme.
    Perhaps u want to bring it in nice view for others, cause.. i cant ๐Ÿ˜€
    https://pastebin.com/N6wfU6m6
    (sorry for post again, i used my wrong mail)

    1. Awesome ๐Ÿ™‚

  21. Hi, I plugged in the snippet and it does display all the stock variables but the all the stock quantity are set to “1 in stock”. They don’t reflect my actual stock quantities. Any Ideas?

    1. Thanks for your comment Mike ๐Ÿ™‚ It works for me, so are you using the latest WooCommerce, are all your variations set to “Manage Stock” and not to “Sold Individually”?

  22. Is there a way to make the stocks for each variation only appear when that variation is selected? Like here, when they pick Size 4 it will show only the stock of size 4, then when they click size 3 only size 3 stock will show and size 4 stock will disappear. Thanks ๐Ÿ™‚

    1. Hello Amiel, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  23. Hey ###, nice snippet! Thanks alot.
    I tried to get it work, like you mentioned it to David, on a single product page. I changed the hook, but it does not work for me.

    I changed the hook line to:
    add_action( ‘woocommerce_before_add_to_cart_button’, ‘bbloomer_echo_stock_variations_loop’, 5 );
    What am i doing wrong? Sorry for noobing around!

    Cheers,
    Janos

    1. Janos, thanks for your comment ๐Ÿ™‚ It should work, so maybe try to use a different hook – take a look at https://businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/

  24. Hi, thanks for the snippet.
    It breaks in PHP 7.2
    You can check?
    Thanks!

    1. You were absolutely right Toni, thank you ๐Ÿ™‚ Snippet has now been updated!

  25. I tried the code and nothing happens. I’m trying to change the Loop/Shop/Category pages, but for what ever reason(s), it’s not changing the output. I’d like to show both product variations and their prices (instead of 1 which is WooCommerce Default) underneath the in the “woocommerce_shop_loop_item_title”. I’m not using PHP 7, but using PHP version 5.6.34. Just to test that it works I first tried to only show the product variation, but nothing happens. Not sure what to do WP and WooCommerce at times are difficult to fully understand.

    1. Hey Tom, thanks so much for your comment! Try testing on a different theme, it could be your current one is heavily overriding default WooCommerce functions. Hope this helps

  26. At first it was working for me but what changes i did i am not sure it is breaking my shop

    1. Hey Ghost, thanks so much for your comment! I just retested this on the latest version of WooCommerce and it still works. Unfortunately this looks like custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  27. Is it possible to show / view variation name and price on front / shop page?

    1. Hey Peter, thanks so much for your comment! I suggest you take a look at “conditional logic”: https://businessbloomer.com/conditional-logic-woocommerce-tutorial/ and https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Let me know ๐Ÿ™‚

    2. Thanks for the tips and I will try.

  28. Hi, how do I change the snippet in order to have the stock/variations in the SINGLE PRODUCT PAGE instead of the loop page?

    1. Hey Davide, thanks for your comment! You just need to change “hook”, check out these visual hook guides to find out more: https://businessbloomer.com/woocommerce-tips/visual-hook-series/

  29. Hi

    Your Availability plugin is exactly what I need, but exactly what I don’t need either!

    I have too many variations (up to 100 sometimes – especially for trousers, which comes in colours, waist sizes and leg lengths) per product to display under my Add to Cart button. I would rather include the table in its own tab, next to the description. And possibly have a filter to choose the variation attribute (eg colour) then choose which colour (plus an option for ‘all colours’) and only show the sizes and leg lengths for that colour trouser in the table.

    Alternatively, muslti-select filters could be set for all attributes (colour, waist and leg) so users can choose various options and then click a button called show table, which would then update via ajax.

    I’d pay for this pro version of your plugin, and I know many people would appreciate it. Especially these guys (who you could market it to)

    1. Thanks for your comment Bali ๐Ÿ™‚ This custom work would be quite expensive, so I’m not sure this would be affordable to do based on your budget. If you’re interested please go to the contact page and submit your job proposal. Thank you in advance!

  30. Hey! Great snippet, thank you ๐Ÿ™‚

    I only have 1 problem – I’m using this for showing available clothes sizes, and for some reason, it shows the second smallest size first, then the smallest, and then the 3rd smallest and so on – as you see in this screenshot: https://imgur.com/ELP7g7A

    I’ve tried to sort the string like this:
    $attr_string[] = $attr_value;
    sort($attr_string);

    Both with sort, nsort and asort, but nothing works. The only thing I can fix it is to manually edit variation order for each product in WooCommerce, but as we have 455 products, that’s really not an option.

    I hope you can help me!
    Thomas

    1. Hey Thomas, thanks for your comment! I can’t help you directly via the blog comments, but I can tell you you’re in the right direction. Sorry & thanks for your understanding ๐Ÿ™‚

  31. Hello, thank you for the snippet. It was helpful. However, when I try this snippet with backorders switched on, I am not able to retrieve the max_qty, even when there is available stock. Is this a known issue with Woocommerce?

    1. Royce, thanks so much for your comment! Unfortunately this is custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  32. Hi Rodolfo,
    Nice snippet!
    I try customizing your snippet, when a variation is out of stock it displays only ‘OUT OF STOCK’.
    Is this possible with your snippet, or is this a lot of customizing?
    The reason is that the WooCommece filter has an issue with variable products:
    (https://wordpress.org/support/topic/hide-out-of-stock-variations-when-filtering/)

    1. Hey Christophe, thanks for your comment! Yes, if from the settings you decide to display out of stock products, then my snippet will work ๐Ÿ™‚

  33. Rodolfo,

    I have been searching everywhere but cant find a solution to the following issue. I have a client that want to show multiple products on a single page “category” page (that is the easy bit). But they want the variations of those products to be dropdown so selection and add to cart can be done on the same page. They do not wish for their customers to go to the individual single pages to add to cart and then have to return back to the “category” page. They also need the minimum qty to be set to “8”. Do you know of a script that can do this? OR could you suggest a way it can be done and at what cost?

    1. Hey Mark, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here on the blog. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  34. Rodolfo, thanks. It works, but it display the slug that could not have ‘,’ or ‘.’ for character as I want. How can I display the name of the variation instead of the slug?

    1. Hey Panagiotis, thanks for your comment! You will need to see what’s inside $key[‘attributes’] to get what you need. I suggest using something similar to this https://businessbloomer.com/woocommerce-see-whats-inside-order-array-print_r/

  35. One more, if a variation is out of stock, the shop still displat “in stock” albeit without any count value. Are you able to amend the code to basically hide any out of stock variations?

    Thanks

    1. Good idea Huzaifah! I now changed the snippet and added an if > else to make sure when stock is 0 the “out of stock” message gets echoed instead. Cheers ๐Ÿ™‚

  36. Hi, it works for me.

    However, is there any ways to make it simpler: just to show available variations without its individual stock counts (eg: “Available in S,L,XL”)

    1. Hey Huzaifah, yes, this is possible but I can’t provide a fix here in the blog comments as it is custom work. Thanks for your understanding!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *