Order product collections by stock status, instock products first

  1. This code snippet functions exclusively with the “Default Sorting” option found in WordPress > Customize > WooCommerce > Product Catalog > Default product sorting section. It does not override sorting by price, popularity, or any other criteria set as default.
  2. The snippet sorts products based on their “stock_status” in ascending order (“ASC”). The acceptable values for “stock_status” are “instock,” “outofstock,” and “onbackorder.” Consequently, products will be displayed alphabetically as follows: 1. instock, 2. onbackorder, 3. outofstock.
  3. For this snippet to work effectively, all your products must be utilizing the “Managing Stock” feature in the product edit page under Product Data > Inventory. Otherwise, the behavior of the snippet with products lacking this option is uncertain.

please add this code in the functions.php file in your child theme

add_filter( 'woocommerce_get_catalog_ordering_args', 'bbloomer_first_sort_by_stock_amount', 9999 );

functionbbloomer_first_sort_by_stock_amount( $args) {

   $args['orderby'] = 'meta_value';

   $args['meta_key'] = '_stock_status';

   return$args;

}