bapre
January 8, 2024, 6:24am
1
Hi,
I found a helpful post on this forum on how to set up product sorting.
I’ve successfully implemented sorting following that post, but I’m looking to have both the sorting criteria and the direction in the same dropdown and haven’t been able to figure that out. Has anyone managed to achieve this? I’d love to know how it can be done
1 Like
Magnus
November 21, 2024, 3:12pm
2
Have you found a solution for this yet?
At the moment, the values can be dynamically drawn from the filter dropdowns individually but it will require some custom code to make it work with a single dropdown.
In the most recent preview @Louis did in his youtube live, he demoed some new features with dynamic content / data that may possibly allow this to be done more easily when it is released.
Magnus
November 28, 2024, 7:03pm
4
Okay, thank you.
Here is the solution which I made. Maybe someone else can use it.
Cwicly provides a filter which can be used to modify the query args before they are processed by the Cwicly query block: https://docs.cwicly.com/miscellaneous/filters#query-args
I have added the following code to themes function.php (Tools -> Theme File Editor -> Theme Functions
)
It gives me the ability to sort products by:
Popularity
Price (High to Low)
Price (Low to High)
Discount
Newest
Name
My main product query block id is main-product-query
.
add_filter( 'cwicly/query/args', function( $query_args, $attributes, $id ) {
if($id === 'main-product-query') {
// Map sorting options to WooCommerce orderby and order parameters
$sorting_options = [
'product-popularity' => ['orderby' => 'meta_value_num', 'meta_key' => 'total_sales', 'order' => 'DESC'],
'product-price-desc' => ['orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'DESC'],
'product-price-asc' => ['orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'ASC'],
'product-discount' => ['orderby' => 'meta_value_num', 'meta_key' => '_sale_price', 'order' => 'DESC'], // Requires custom discount meta field
'product-newest' => ['orderby' => 'date', 'order' => 'DESC'],
'product-name' => ['orderby' => 'title', 'order' => 'ASC'],
];
if ( isset($sorting_options[$query_args['orderby'] ?? '']) ) {
$selected_sorting = $query_args['orderby'];
// Extract orderby, meta_key, and order for the selected sorting option
$orderby = $sorting_options[$selected_sorting]['orderby'];
$order = $sorting_options[$selected_sorting]['order'];
$meta_key = isset($sorting_options[$selected_sorting]['meta_key']) ? $sorting_options[$selected_sorting]['meta_key'] : null;
$query_args['meta_key'] = $meta_key;
$query_args['orderby'] = $orderby;
$query_args['order'] = $order;
}
}
return $query_args;
}, 10, 3 );
Sorting Select:
Main Product Query:
Working example:
2 Likes