Show Out-of-Stock Products Last
Keeps your shop and category pages sorted as usual but moves sold-out products to the end of the list, so shoppers see what they can buy first.
Opens WPIDE on
Code
add_filter( 'posts_clauses', function ( $clauses, $query ) {
global $wpdb;
if ( is_admin() || ! $query->is_main_query() ) {
return $clauses;
}
if ( ! ( $query->is_post_type_archive( 'product' ) || $query->is_tax( get_object_taxonomies( 'product' ) ) ) ) {
return $clauses;
}
$lookup = $wpdb->prefix . 'wc_product_meta_lookup';
if ( false === strpos( $clauses['join'], 'wpide_stock_sort' ) ) {
$clauses['join'] .= " LEFT JOIN {$lookup} AS wpide_stock_sort ON {$wpdb->posts}.ID = wpide_stock_sort.product_id ";
}
$order = "CASE WHEN wpide_stock_sort.stock_status = 'outofstock' THEN 1 ELSE 0 END ASC";
$clauses['orderby'] = $clauses['orderby'] ? $order . ', ' . $clauses['orderby'] : $order;
return $clauses;
}, 20, 2 );
Notes
Works with every sorting option because it only adds a first sort key on stock status.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.