25% off ProSNIPC25OFF

Sort Out-of-Stock Products Last in Catalog

Pushes out-of-stock WooCommerce products to the end of shop and archive loops while preserving the existing sort order for in-stock items.

PHPby SnipCraft
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) {
    return;
}

add_filter( 'posts_clauses', 'scseed_out_of_stock_last', 10, 2 );
function scseed_out_of_stock_last( $clauses, $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return $clauses;
    }
    if ( ! ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) {
        return $clauses;
    }
    global $wpdb;
    $clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS scseed_stock_pm
        ON ( {$wpdb->posts}.ID = scseed_stock_pm.post_id
             AND scseed_stock_pm.meta_key = '_stock_status' )";
    $existing        = $clauses['orderby'] ? $clauses['orderby'] : "{$wpdb->posts}.post_date DESC";
    $clauses['orderby'] = "CASE WHEN scseed_stock_pm.meta_value = 'outofstock' THEN 1 ELSE 0 END ASC, {$existing}";
    return $clauses;
}
#catalog#products#sorting#stock#woocommerce