Move / Show Out of stock products at the end in Woocommerce

Sometimes we will have few “Out of Stock” products and those comes up on top of product list, which make users hard to find proper product when there are few “Out of Stock” products and force them to navigate to multiple pages. So here is the simple script to move / show “Out of Stock” product at the end of product list in WooCommerce.

You need to add this below code, end of functions.php in your theme.

add_action( 'pre_get_posts', 'move_out_of_stock_products_to_end' );
function move_out_of_stock_products_to_end( $q ) {
// checks whether it is product query or skip next steps
if ( (!isset($q->query_vars['wc_query']) && !isset($q->query_vars['post_type']))
	|| ($q->query_vars['wc_query'] != 'product_query' && $q->query_vars['post_type'] != 'product')
	|| is_admin() ) return;
// this code just adds postmeta table into search query
$q->set( 'meta_query', array(array(
'key' => '_stock_status',
'value' => '',
'compare' => 'NOT IN'
)));
// filter to handle final post request
add_filter( 'posts_request', 'add_stock_status_in_request' );
// filter to handle additional post fields in select statement
add_filter('posts_fields', 'add_stock_status_in_post_fields', 10, 2);
remove_action( 'pre_get_posts', 'move_out_of_stock_products_to_end' );
}
function add_stock_status_in_post_fields( $fields, $query ) {
$fields .= ", IF(mt1.meta_value = 'instock', 10, 5) as stock_status";
remove_filter('posts_fields', 'add_stock_status_in_post_fields');
return $fields;
}
function add_stock_status_in_request( $input ) {
if (preg_match("@\((.*?)\.meta_key = '_stock_status'@i", $input, $table_name)) {
$input = str_ireplace("mt1.", $table_name[1] . '.', $input);
}
$input = str_ireplace("ORDER BY", "ORDER BY stock_status DESC,", $input);
return $input;
}

5 thoughts on “Move / Show Out of stock products at the end in Woocommerce

  1. Works in catalog, but looks like it breaks the woocommerce shortcodes. But is good, need some more work. If find the solution gonna post there.

Leave a Reply

Your email address will not be published. Required fields are marked *

*