Show How Many Products Left in Stock WooCommerce

This PHP code enables you to add custom stock status messages based on inventory settings on single product pages in WooCommerce.

Add the code to the end of your child themes functions file or custom functionality/code snippets plugin.

How The Code Works

Display Stock Quantity Code :

  • The code hooks into the woocommerce_before_add_to_cart_button action, meaning it will execute the display_stock_quantity function before the “Add to Cart” button on the product page.
  • The `display_stock_quantity` function is responsible for checking the stock status of the product and displaying a custom message accordingly.
  • It checks if WooCommerce is active using class_exists( 'WooCommerce' ).
  • It checks if stock management is unchecked using $product->get_manage_stock(). If unchecked and the product is in stock, it echoes a custom message “Not many left.”
  • For variable products, it retrieves the stock quantity for each variation and displays a message based on the quantity.
  • For simple products, it directly gets the stock quantity and displays a message.

Remove Default Stock Status Code :

  • The code hooks into the woocommerce_get_stock_html filter, meaning it will filter the HTML for the stock status.
  • The remove_default_stock_status function is responsible for checking if stock management is enabled for the product.
  • If stock management is enabled, it sets the HTML to an empty string, effectively removing the default stock status message.

Summary :

  • The first part of the code (display_stock_quantity) adds a custom stock display message based on the product’s stock status.
  • The second part of the code (remove_default_stock_status) removes the default stock status message for products where stock management is enabled.

These 2 code snippets work together to customize the display of stock inventory information on your WooCommerce single product pages.

Related Code Snippets

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.