Reputation: 21
I'm trying to get the ability to sort products on a product category page in Woocommerce by their average rating.
I've found the code to place the rating on product page, added code to functions.php (see below) but the selecting rating doesn't do anything.
What is the meta_key that I need to call on (or create) to get this to work?
add_filter('woocommerce_get_catalog_ordering_args','custom_woocommerce_get_catalog_ordering_args');
function custom_woocommerce_get_catalog_ordering_args( $args ) {
if (isset($_SESSION['orderby'])) {
switch ($_SESSION['orderby']) :
case 'date_asc' :
$args['orderby'] = 'date';
$args['order'] = 'asc';
$args['meta_key'] = '';
break;
case 'price_desc' :
$args['orderby'] = 'meta_value_num';
$args['order'] = 'desc';
$args['meta_key'] = '_price';
break;
case 'title_desc' :
$args['orderby'] = 'title';
$args['order'] = 'desc';
$args['meta_key'] = '';
break;
case 'rating_desc' :
$args['orderby'] = 'rating';
$args['order'] = 'desc';
$args['meta_key'] = '';
break;
endswitch;
}
return $args;
}
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');
function custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['rating_desc'] = 'Rating';
$sortby['title_desc'] = 'Reverse-Alphabetically';
$sortby['price_desc'] = 'Price (highest to lowest)';
$sortby['date_asc'] = 'Oldest to newest';
return $sortby;
}
Upvotes: 2
Views: 3635
Reputation: 33
Use WC_Shortcode_Products
to generate the wc loop with sort parameters were used at default wc shop page:
for($i=1;$i<=$num;$i++){
$atts = array_merge(array(
'columns' => $columns,
'orderby' => $order_by,
'order' => $sort_by,
'rows' => $rows,
'page' => $i,
));
$shortcode = new WC_Shortcode_Products($atts, 'recent_products');
$html ='';
$html .= $shortcode->get_content();
echo $html;
}
Upvotes: 0
Reputation: 66
Try changing your case 'rating_desc' to this
case 'rating_desc' :
add_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) );
break;
Found that piece of code in includes\class-wc-query.php at line 492 onward after some digging when I had a similar issue. If you need the core function order_by_rating_post_clauses, it's in the same file at line 547.
Hope it helps!
Upvotes: 2