Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.