'Multiple order by in WooCommerce

I want to order my products in category page by average rating (DESC) and then by price (ASC).

| id  |  avgrating   |   price   |
|  1  |      4       |     10    |
|  2  |      4       |      5    |
|  3  |      5       |      7    |

Order: 3, 2, 1.

So I tried with:

$args['meta_key'] = '_wc_average_rating';
$args['orderby']  = array(
    'meta_value_num' => 'DESC',
    'price' => 'ASC',
);

But they aren't ordered (also) by price. I also replaced price with _price, same result.

I'm using latest version of WordPress (4.8) and WooCommerce (3.0.8).

Edit:

If I use:

$args['meta_key'] = '_wc_average_rating';
$args['orderby']  = array(
    'meta_value_num' => 'DESC',
    'ID'             => 'DESC',
);

Order works as excepted, DESC by average rating and then DESC by ID. So, I have to change ID with price but I can't make it work.



Solution 1:[1]

Check by passing the order with arguments

Check with these,

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'sort_by_type' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num title';
        $args['order'] = 'ASC';
        $args['meta_key'] = 'sort_by_type';

    }

    if ( '_wc_average_rating' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num title';
        $args['order'] = 'DESC';
        $args['meta_key'] = '_wc_average_rating';
    }

    return $args;
}

Solution 2:[2]

I would like to order product first by date then out of stock items be at the end. I tried the below code. but doesn't work.

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'sort_by_date' == $orderby_value ) {
$args['orderby'] = 'meta_value';
$args['order'] = 'ASC';
$args['meta_key'] = 'sort_by_date';

}
if ( '_stock_status' == $orderby_value ) {
$args['orderby'] = 'meta_value';
 $args['order'] = 'DESC';
$args['meta_key'] = '_stock_status';
}
 return $args;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Shaar