Woocommerce displays the Stock Status, for example ‘Out of stock’ or ‘6 in stock’ on the single product page. I needed to display the message on the Shop and Category pages. Also my client actually only wanted to display the status when a product was ‘Out of stock’
Thanks to Bryce from Woocommerce for help with this.
There is a very convenient action hook ‘woocommerce_after_shop_loop_item_title’ which runs as it implies after the product title is displayed by the loop on shop pages. For more on action hooks see the note panels below the code. So we need a function to display the stock status and then to connect to this action hook. This goes in your functions file which should be in your Child theme. For more on Child themes see the note panel below the code.
If you want to display the ‘in stock’ messages as well, in the code below just leave out this, == ‘Out of stock’
<?php //add action give it the name of our function to run add_action( 'woocommerce_after_shop_loop_item_title', 'wcs_stock_text_shop_page', 25 ); //create our function function wcs_stock_text_shop_page() { //returns an array with 2 items availability and class for CSS global $product; $availability = $product->get_availability(); //check if availability in the array = string 'Out of Stock' //if so display on page.//if you want to display the 'in stock' messages as well just leave out this, == 'Out of stock' if ( $availability['availability'] == 'Out of stock') { echo apply_filters( 'woocommerce_stock_html', '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>', $availability['availability'] ); } }
Action hooks:
Woocommerce uses action hooks. See the Woocommerce Codex and the WordPress Codex and this excellent article for more information.
The numbers at the end of the lines, in this case 25, effect the order in which things run, lower numbers first, thus effecting where they appear. More on priority can be found here
Child Themes:
You want to change code in a way that will not be over-written when you update your theme. So if you do not already have one you should setup a child theme. I always do this if I am making any changes to the main theme, even if it is only CSS. That is not the topic of this post so here is a link to a tutorial on creating a child theme, you will find the WordPress codex article here.