Reputation: 23
I am trying to change the name of the default order by, add a new order by for name, and remove several of the default options that are not relevant:
// Remove the other sort order options and add and rename 1
add_filter('woocommerce_catalog_orderby', 'change_default_sorting_options');
function change_default_sorting_options($options)
{
unset($options['popularity']);
unset($options['rating']);
unset($options['date']);
unset($options['price']);
unset($options['price-desc']);
$options['name'] = 'Sort by Name';
$options['menu_order'] = 'Catalog Sort Order';
return $options;
}
this works fine. The default is the menu_order option.
Then I want to have the catalog sort by "name" when the category is "20 Gauge". Adding this code results does sort by name for the "20 Gauge" category but it removes the default option (menu_order) from the sort order dropdown:
add_filter('woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby');
function custom_default_catalog_orderby()
{
if (is_product_category(array('20-gauge'))) {
return 'name'; // sort by latest
} else {
return 'menu_order';
}
}
Upvotes: 2
Views: 1308
Reputation: 253919
You need a little magic trick more. Try the following revisited code:
// Remove the other sort order options and add and rename 1
add_filter( 'woocommerce_catalog_orderby', 'change_default_sorting_options' );
function change_default_sorting_options( $options ){
unset($options['popularity'], $options['rating'], $options['date' ], $options['price'], $options['price-desc']);
$menu_order = __('Catalog Sort Order');
$options['name'] = __('Sort by Name');
if ( is_product_category( array( '20-gauge') ) ) {
$options[ 'menu_order2' ] = $menu_order;
} else {
$options[ 'menu_order' ] = $menu_order;
}
return $options;
}
add_filter( 'woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby' );
function custom_default_catalog_orderby( $orderby ) {
if (is_product_category( array( '20-gauge') ) ) {
$orderby = 'name'; // sort by latest
}
return $orderby;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_non_default_sorting_by_menu_order' );
function enable_non_default_sorting_by_menu_order( $args ) {
if ( isset( $_GET['orderby'] ) && 'menu_order2' == $_GET['orderby'] ) {
$args['orderby'] = 'menu_order title';
}
return $args;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Upvotes: 3