Show Out of stock products at the end in WooCommerce - excluding backorder

Viewed 197

Please note the difference in my request to the other similar questions. This snippet works to keep Out of Stock items at the bottom:

Show Out of stock products at the end in Woocommerce

add_filter('posts_clauses', 'order_by_stock_status');
function order_by_stock_status($posts_clauses) {
    global $wpdb;
    // only change query on WooCommerce loops
    if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy())) {
        $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
        $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
        $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
    }
    return $posts_clauses;
}

However, I want to exclude backorder status and simply consider products on backorder as instock, so they remain in the same position as if they were in stock. I think the difference will be in the JOIN but I am unclear on the SQL required.

1 Answers
/**
 * Sort Products By Stock Status - WooCommerce Shop
 */
 
add_filter( 'woocommerce_get_catalog_ordering_args', 'shop_sort_by_stock_amount', 9999 );
 
function shop_sort_by_stock_amount( $args ) {
   $args['orderby'] = 'meta_value';
   $args['meta_key'] = '_stock_status';
   return $args;
}

This snippet sorts products by stock_status in ASC (ascending) order. Possible values are instock outofstock onbackorder so it will automatically display them alphabetically like this: 1.instock 2.onbackorder 3.outofstock

Related