There might be situations that you want to move “out-of-stock” products to end of the list, to do this we need to modify the WP_Query
associated with the products list you.
Moving out of stock products to the end
Moving out of stock products to the end of the list is a common practice in ecommerce website, to achieve this you need to use woocommerce_product_query
hook to modify the query
If you’re using WooCommerce default sorting configuration, all you need to do is to sort the list by _stock_status
meta key which indicates availability of products:
add_filter('woocommerce_get_catalog_ordering_args', 'aminnz_instock_products_first', 9999);
if (!function_exists(('aminnz_instock_products_first'))) {
function aminnz_instock_products_first($args)
{
$args['orderby'] = 'meta_value';
$args['meta_key'] = '_stock_status';
return $args;
}
}
However in most cases you have another ordering criteria (for example by date) in such cases you need one extra thing needs to be added to orderby
part, For example if you need to sort products by their modified date (modified products first) and then move out of stock products to the end, you need to change the above code like this:
add_filter('woocommerce_get_catalog_ordering_args', 'aminnz_instock_products_first', 9999);
if (!function_exists(('aminnz_instock_products_first'))) {
function aminnz_instock_products_first($args)
{
$args['orderby'] = ['meta_value' => 'ASC', 'modified' => 'DESC'];
$args['meta_key'] = '_stock_status';
return $args;
}
}
You can check WP_Query docs for more possible options