How to display In-Stock Products First in WooCommerce

How to display In-Stock Products First in WooCommerce

WooCommerce has a feature that allows you to manage your stock availability. Now the inventory of some of your goods is very low and naturally, after the purchase, their inventory will be zero.

In this case, to improve the quality of work with your store, it is better to display non-existent products at the bottom of your product list. And display the In-Stock products at the beginning of the list.

Stock management in WooCommerce

To manage the inventory of your products, just enter the products section and edit one of the products on your site.

Now just go to the product information section and activate inventory management from the inventory list section.

Enter your inventory here. For example, if you enter a value of 50, after 50 units of this product are sold, the inventory is displayed as non-existent. In such cases, you must display these products at the bottom of the list of products on your website.

Display In-Stock Products First

Once the inventory is zero, we have a variable called _stock_status in WooCommerce that will change this non-existent state. In such cases, we can display the products at the bottom of the list based on the lack of inventory.

To display non-existent products at the bottom of the product list, just go to Themes > Theme Editor.

Then open the functions.php file or theme functions from the left.

In the second line of this file, enter the following code and save the file.

add_filter( 'woocommerce_get_catalog_ordering_args', 'mihanwp_sort_by_stock', 9999 );
 
function mihanwp_sort_by_stock( $args ) {
   $args['orderby'] = 'meta_value';
   $args['order'] = 'ASC';
   $args['meta_key'] = '_stock_status';
   return $args;
}

If this file could not be changed through the wordpress admin panel, see the tutorial on changing the wordpress template code.

Just as easily! By entering the above code, wordpress was instructed to display the non-existent products at the bottom of the product list. 🙂

Good luck. And be happy. 😉

What do you think about this?

Please submit your comment only on the subject of this article. Your questions will be answered by the community.

Ask Question