2 回答

TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個(gè)贊
首先,您需要'rating-asc'在掛鉤中的自定義函數(shù)中定義排序選項(xiàng)參數(shù)woocommerce_get_catalog_ordering_args。
由于存在排序選項(xiàng)“按平均評(píng)級(jí)排序”,如果您希望按“評(píng)級(jí)”鍵對(duì)產(chǎn)品進(jìn)行排序的默認(rèn)現(xiàn)有參數(shù),您將擁有該數(shù)組:
$args = array(
'orderby' => array(
'meta_value_num' => 'DESC',
'ID' => 'ASC'
),
'order' => 'ASC',
'meta_key' => '_wc_average_rating'
);
所以你只需要更改'meta_value_num' => 'DESC'為'meta_value_num' => 'ASC',那么你正確的工作代碼將如下所示:
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;
}
現(xiàn)在,您可以在“按平均評(píng)分排序”現(xiàn)有選項(xiàng)之后插入新的排序選項(xiàng),例如:
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;
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的 function.php 文件中。經(jīng)過(guò)測(cè)試并有效。

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的代碼應(yīng)該僅適用于將排序選項(xiàng)添加到下拉列表,但如果您希望它生效,您需要通過(guò)向目錄產(chǎn)品查詢添加正確的參數(shù)來(lái)將其鏈接到元鍵或其他內(nèi)容,如下所示:
add_filter( 'woocommerce_get_catalog_ordering_args', 'rory_custom_sorting_args' );
function rory_custom_sorting_args( $args ) {
if( isset( $_GET['orderby'] ) && 'rating-asc' === $_GET['orderby'] ) {
$args['meta_key'] = 'rating-asc'; // Replace this with the meta key you want to use for ordering products
$args['orderby'] = array( 'meta_value' => 'ASC' );
}
return $args;
}
- 2 回答
- 0 關(guān)注
- 171 瀏覽
添加回答
舉報(bào)