将自定义产品排序设置为默认的Woocommerce排序选项 [英] Set custom product sorting as default Woocommerce sorting option
问题描述
在Woocommerce中,我使用了以下代码,该代码按修改的日期向商店目录添加了自定义排序选项.
In Woocommerce, I ma using the following code that adds a custom sorting option to shop catalog by modified date.
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' );
function enable_catalog_ordering_by_modified_date( $args ) {
if ( isset( $_GET['orderby'] ) ) {
if ( 'modified_date' == $_GET['orderby'] ) {
return array(
'orderby' => 'modified',
'order' => 'DESC',
);
}
}
return $args;
}
add_filter( 'woocommerce_catalog_orderby', 'add_catalog_orderby_by_modified_date' );
function add_catalog_orderby_by_modified_date( $orderby_options ) {
// Rename 'menu_order' label
$orderby_options['modified_date'] = __("Sort by modified date", "woocommerce");
return $orderby_options ;
}
来自此答案:按修改日期添加排序在Woocommerce产品中的排序方式
我想将该自定义排序选项作为默认排序选项,同时将默认的woocommerce选项(按菜单顺序)作为次要选项.
I would like to make that custom sorting option as the default sorting option keeping the default woocommerce option (by menu order) as a secondary option.
如何将这种排序设置为woocommerce默认设置?
How can I set this sorting as woocommerce default?
推荐答案
您将使用以下与版本稍有不同的版本代码,并附带一些其他挂钩函数:
You will use the following slight different version code, with some additional hooked functions:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' );
function enable_catalog_ordering_by_modified_date( $args ) {
if ( isset( $_GET['orderby'] ) ) {
if ( 'modified_date' == $_GET['orderby'] ) {
return array(
'orderby' => 'modified',
'order' => 'DESC',
);
}
// Make a clone of "menu_order" (the default option)
elseif ( 'natural_order' == $_GET['orderby'] ) {
return array( 'orderby' => 'menu_order title', 'order' => 'ASC' );
}
}
return $args;
}
add_filter( 'woocommerce_catalog_orderby', 'add_catalog_orderby_modified_date' );
function add_catalog_orderby_modified_date( $orderby_options ) {
// Insert "Sort by modified date" and the clone of "menu_order" adding after others sorting options
return array(
'modified_date' => __("Sort by modified date", "woocommerce"),
'natural_order' => __("Sort by natural shop order", "woocommerce"), // <== To be renamed at your convenience
) + $orderby_options ;
return $orderby_options ;
}
add_filter( 'woocommerce_default_catalog_orderby', 'default_catalog_orderby_modified_date' );
function default_catalog_orderby_modified_date( $default_orderby ) {
return 'modified';
}
add_action( 'woocommerce_product_query', 'product_query_by_modified_date' );
function product_query_by_modified_date( $q ) {
if ( ! isset( $_GET['orderby'] ) && ! is_admin() ) {
$q->set( 'orderby', 'modified' );
$q->set( 'order', 'DESC' );
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试和工作.
Code goes in function.php file of your active child theme (or active theme). Tested and work.
这篇关于将自定义产品排序设置为默认的Woocommerce排序选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!