Home:ALL Converter>Add products sorting option by star rating ASC in Woocommerce

Add products sorting option by star rating ASC in Woocommerce

Ask Time:2020-07-12T21:50:09         Author:Rory

Json Formatter

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;
 
}

Author:Rory,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62861888/add-products-sorting-option-by-star-rating-asc-in-woocommerce
LoicTheAztec :

First you need to define 'rating-asc' sorting options arguments in a custom function hooked in woocommerce_get_catalog_ordering_args hook.\nAs sorting option "Sort by average rating" exists, if you look to default existing arguments for sorting products by "rating" key, you have that array:\n$args = array(\n 'orderby' => array(\n 'meta_value_num' => 'DESC',\n 'ID' => 'ASC'\n ),\n 'order' => 'ASC',\n 'meta_key' => '_wc_average_rating'\n);\n\nSo you just need to change 'meta_value_num' => 'DESC' to 'meta_value_num' => 'ASC', then your right working code is going to be like:\nadd_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_ratings' );\nfunction enable_catalog_ordering_by_ratings( $args ) {\n if ( isset( $_GET['orderby'] ) && 'rating-asc' === $_GET['orderby']\n && isset($args['orderby']['meta_value_num']) ) {\n $args['orderby']['meta_value_num'] = 'ASC';\n }\n return $args;\n}\n\nNow you can insert your new sorting option just after "Sort by average rating" existing one like:\nadd_filter( 'woocommerce_catalog_orderby', 'catalog_orderby_ratings_asc_filter' );\nfunction catalog_orderby_ratings_asc_filter( $options ){\n $sorted_options =[];\n\n foreach( $options as $key => $label ){\n if( 'rating' === $key ) {\n $sorted_options['rating'] = $options['rating'] . ' ' . __('(Desc)', 'woocommerce');\n $sorted_options['rating-asc'] = $options['rating'] . ' ' . __('(Asc)', 'woocommerce');\n } else {\n $sorted_options[$key] = $label;\n }\n }\n\n return $sorted_options;\n}\n\nCode goes in function.php file of your active child theme (or active theme). Tested and works.\n\nRelated:\n\nAdd a new custom default ordering catalog option in Woocommerce\nSet custom product sorting as default Woocommerce sorting option\n",
2020-07-12T15:30:59
yy