I need to sort my products by rating in a wp_query loop:
this is my code:
switch($ordering){
case 'default':
$meta_key = '';
$order="asc";
$orderby = 'menu_order title';
break;
case 'popularity':
$meta_key = '';
$order="desc";
$orderby = 'total_sales';
break;
case 'low_to_high':
$meta_key = '_price';
$order="asc";
$orderby = 'meta_value_num';
break;
case 'high_to_low':
$meta_key = '_price';
$order="desc";
$orderby = 'meta_value_num';
break;
case 'newness':
$meta_key = '';
$order="desc";
$orderby = 'date';
break;
case 'rating':
$meta_key = '';
$order="desc";
$orderby = 'rating';
break;
}
$args_products_sorting = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => $orderby,
'order' => $order,
'meta_key' => $meta_key
);
Where is the error ?
If i set in url ?orderby=rating
it works correctly.
Thanks.
5 s
You should use 'orderby' => 'meta_value_num'
and 'meta_key' => 'rating'
as specified by the WordPress Codec. Using meta_value_num
with the assumption your ratings are numeric values
Reference: Orderby Parameters