First you need to define 'rating-asc'
sorting options arguments in a custom function hooked in woocommerce_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:
$args = array(
'orderby' => array(
'meta_value_num' => 'DESC',
'ID' => 'ASC'
),
'order' => 'ASC',
'meta_key' => '_wc_average_rating'
);
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:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_ratings' );
function enable_catalog_ordering_by_ratings( $args ) {
if ( isset( $_GET['orderby'] ) && 'rating-asc' === $_GET['orderby']
&& isset($args['orderby']['meta_value_num']) ) {
$args['orderby']['meta_value_num'] = 'ASC';
}
return $args;
}
Now you can insert your new sorting option just after "Sort by average rating" existing one like:
add_filter( 'woocommerce_catalog_orderby', 'catalog_orderby_ratings_asc_filter' );
function catalog_orderby_ratings_asc_filter( $options ){
$sorted_options =[];
foreach( $options as $key => $label ){
if( 'rating' === $key ) {
$sorted_options['rating'] = $options['rating'] . ' ' . __('(Desc)', 'woocommerce');
$sorted_options['rating-asc'] = $options['rating'] . ' ' . __('(Asc)', 'woocommerce');
} else {
$sorted_options[$key] = $label;
}
}
return $sorted_options;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Related: