How to Hide Out of Stock Products in WooCommerce

WooCommerce Hide Out of Stock ProductsWoocommerce provides users with an excellent inventory management system that helps build an eCommerce website within the shortest time possible. One of the most important requirements for inventory management in eCommerce is an option to hide out of stock products. Luckily WooCommerce comes with an out-of-box solution to hide out of stock products in the settings.

If you are, a WooCommerce developer looking for a code solution, you can also implement the solution in the code. In this post, I will share both options so that you can use the option that best suits your needs.

WooCommerce Hide Out of Stock Products

In WooCommerce hide out of stock products using the option provided in the product settings that do not require you to add any code in your theme or plugin.

Steps to Hide Out of Stock Products in Single Product

  1. Go to WooCommerce -> Settings submenu in the WordPress dashboard
  2. Click on the Products Tab > Inventory sub-tab
  3. Check the option Out Of Stock Visibility that hides the out of stock products

Navigate to the WooCommerce dashboard menu and user the Products tab click on inventory sub-tab to see the option to hide out of stock products as shown in the image below:

WooCommerce Hide Out of Stock Products

Check on this option and save the settings and you will successfully hide the out of stock products from the catalog.

Alternative Way to Hide WooCommerce Out of Stock Products 

For WooCommerce theme developers or plugin developers, a code solution can also come in handy when you want to auto hide out of stock products.

You can add an action hook that hooks on pre_get_posts and the callback function should have the logic to hide the out of stock product using a taxonomy query. Here is an example of code snippet that works perfectly for hiding the out of stock products:

<?php

add_action( 'pre_get_posts', 'njengah_hide_out_of_stock_products' );

function njengah_hide_out_of_stock_products( $query ) {

  if ( ! $query->is_main_query() || is_admin() ) {
    return;
  }

     if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {

     $tax_query = (array) $query->get('tax_query');

      $tax_query[] = array(
      'taxonomy' => 'product_visibility',
      'field' => 'term_taxonomy_id',
      'terms' => array( $outofstock_term->term_taxonomy_id ),
      'operator' => 'NOT IN'
   );

  $query->set( 'tax_query', $tax_query );

}

  remove_action( 'pre_get_posts', 'njengah_hide_out_of_stock_products' );

}

This code should be added to the theme or child theme functions.php file or your plugin files.

Wrapping up

If you want to quickly hide the out of stock product in WooCommerce, there is no need to reinvent the wheel. The option provided by default in WooCommerce provides the best and easiest solution without editing a line of code!

Comments are closed.