I'm building an online shop with Wordpress - Woocommerce and facing on a issue with categories product filtering
My Products Categories looks like this:
Brand
Nike
Adidas
Rebook
Puma
Gender
Male
Female
Type of product
Shoes
Clothes
Accessories
If I select Brand:Nike and Gender:Male, it shows me not only products of Nike with Gender:Male but other brands with gender male also...
Here is what I want to do: If I select Nike, Adidas brands and gender male I want to show only products with nike or adidas brands and gender nike, PS.From some researches I've made on url params is product_cat=nike,adidas -> is like OR if I change manually to product_cat=nike+adidas -> is like AND,
I want to make like hirearchial groups of categories like this to filter product_cat=nike,adidas+male
products are filtered dynamically with AJAX
Do you have any clue or piece of code that I can modify (NOT PLUGIN) to do it? without custom taxonomies!?
Thanks
UPDATED:
Code I tried:
function modify_tax_query( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
$term = get_term_by('slug', get_query_var('s'), 'product_cat');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array($term->slug),
'operator' => 'NOT IN'
),
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars['tax_query'] = $query->tax_query->queries;
$query->set('tax_query', $query->tax_query->queries);
}
}}
add_action( 'pre_get_posts', 'modify_tax_query', 1 );
My Answer:
To create a multiple terms tax query in PHP and modify it, you can use the following code snippet:
php
// Define the tax query arguments
$tax_query_args = array(
'relation' => 'AND', // Use 'AND' for multiple terms
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'term1', 'term2' ),
'operator' => 'IN' // Use 'IN' to include all terms
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => array( 'tag1', 'tag2' ),
'operator' => 'IN' // Use 'IN' to include all terms
)
);
// Modify the tax query arguments
$modified_tax_query_args = array_map(function($tax_query) {
$tax_query['operator'] = 'NOT IN'; // Change the operator to 'NOT IN'
return $tax_query;
}, $tax_query_args);
// Output the modified tax query arguments
var_dump($modified_tax_query_args);
In this code snippet, we first define the tax query arguments with multiple terms for different taxonomies. We then use the `array_map` function to modify the tax query arguments by changing the operator to 'NOT IN'. Finally, we output the modified tax query arguments using `var_dump`.
You can further customize the tax query arguments based on your specific requirements by adjusting the taxonomy, terms, and operator values.
Rate this post
5 of 5 based on 4855 votesComments