Show recent products first but “sold out last” in query

If we only have two stock statuses, namely outofstock and instock, we can very easily achieve sorting with pre_get_posts

add_action( 'pre_get_posts', function ( $q ) {
    if (   !is_admin()                 // Target only front end 
         && $q->is_main_query()        // Only target the main query
         && $q->is_post_type_archive() // Change to suite your needs
    ) {
        $q->set( 'meta_key', '_stock_status' );
        $q->set( 'orderby',  'meta_value'    );
        $q->set( 'order',    'ASC'           );
    }
}, PHP_INT_MAX );

You should adjust that to your needs

Leave a Comment