# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, shop, stock, sorting
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-out-of-stock-last/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show Out-of-Stock Products Last" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
