Hi,
I would like a filter allowing the user to slect many taxonomy item with the result will be only the post having all the terms.
Example: the user select ”vegetable” and ”fruit” and the result is all the products which have BOTH of the terms, Not those which have ”vegetable” plus ”fruit”.
I searched the help but can't find any answer but I'm sure this case was already answered somewhere.
Thx
Hi,
Thank you for contacting us and I'd be happy to assist.
To change the filtering type for a particular taxonomy, to 'AND', you can use a custom function attached to the 'wpv_filter_query' filter:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
Example:
add_filter( 'wpv_filter_query', 'filter_tax_filter_and', 1000 , 3 );
function filter_tax_filter_and( $query_args, $view_settings ) {
// check for specific view
if ( ( isset($view_settings['view_id']) && $view_settings['view_id'] == 12345) ) {
// check if taxonomy query exists
if ( (!empty( $query_args['tax_query'])) ) {
// check for target taxonomy
for ($i=0; $i < (count($query_args['tax_query']) - 1) ; $i++) {
// if target taxonomy and more than one terms are selected
if ( ( $query_args['tax_query'][$i]['taxonomy'] == "category") && (count($query_args['tax_query'][$i]['terms']) >= 2) ) {
// change operator to 'AND' from 'IN'
$query_args['tax_query'][$i]['operator']='AND';
}
}
}
}
return $query_args;
}
Note: You'll replace '12345' with your target view's ID and 'category' with your target taxonomy's slug.
The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.
regards,
Waqar
Hello Waqar,
Thx for your help.
I'm afraid I missed something because it seems to not work.
You can see it in action there: hidden link
Select for example Art Deco and Byphasse. Since there is no product with those 2 categories, the result should be 0 but it displays both products with only Art Deco and only Byphasse.
Thx again
To troubleshoot this, I'll need to see how this view and custom code snippet are set up in the admin area.
Can you please share temporary admin login details, along with the details about where this custom code is added?
Note: Your next reply will be private and making a complete backup copy is recommended before sharing the access details.
Thank you for sharing the access details.
In the custom code snippet, I've replaced the taxonomy slug from 'product-cat' to 'product_cat' and the code is working now.
(screenshot: hidden link )
Haw, newbie problem, I'm ashamed.
Many many thx!