Formulate a url to show posts with both taxonomy terms
I would like to show an archive of posts that have two taxonomy terms in common. So for example, I'd like to show all posts that have both the terms sauce and cheese in the custom food
taxonomy.
The trick is that I'd like to do this using the url. The closest I've come is with:
example.com?food[]=saucefood[]=cheese
Upon inspecting the $query from the pre_get_posts
filter, I can see that:
WP_Tax_Query::__set_state(array(
'queries' =
array (
0 =
array (
'taxonomy' = 'food',
'terms' =
array (
0 = 'sauce',
1 = 'cheese',
),
'field' = 'slug',
'operator' = 'IN',
'include_children' = true,
),
),
So then I change the operator
to AND
like so:
add_action('pre_get_posts', function($query) {
$query-tax_query-queries[0]['operator'] = 'AND';
});
But my results are always including posts that have at least one term instead of posts that have all terms.
According to Query Monitor, the main query is as such (and you can see that it's looking for posts that have either of the two term IDs.
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (6,9) )
So, how can I formulate a url to get only posts with both taxonomy-terms?
Topic multi-taxonomy-query pre-get-posts terms wp-query taxonomy Wordpress
Category Web