I’m looking for a way to sort the products by star rating (asc and desc). It seems that i would need to create a custom code for this since something like this for example isn’t implemented in Woocommerce.
$options['rating-asc']
is a the piece of code that doesn’t work/exist but i use it to express the function i’m looking for like $options['title-desc']
.
add_filter( 'woocommerce_catalog_orderby', 'rory_add_custom_sorting_options' );
function rory_add_custom_sorting_options( $options ){
$options['rating-asc'] = 'Rating (Asc)';
return $options;
}
2
Answers
Your code should work only for adding the sorting option to the dropdown, but if you want it to have effect you need to link it to a meta key or something by adding the correct arguments to the catalog products query like this:
First you need to define
'rating-asc'
sorting options arguments in a custom function hooked inwoocommerce_get_catalog_ordering_args
hook.As sorting option "Sort by average rating" exists, if you look to default existing arguments for sorting products by "rating" key, you have that array:
So you just need to change
'meta_value_num' => 'DESC'
to'meta_value_num' => 'ASC'
, then your right working code is going to be like:Now you can insert your new sorting option just after "Sort by average rating" existing one like:
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Related: