tax_query AND relation for same taxonomy
-
I have a custom post type ‘Venue’ and a custom taxonomy ‘Event Category’. I have an array that contains multiple Event Category slugs. The array can contain any number of Event Category slugs based on user input. I am trying to write a query that retrieves only those Venues that have each Event Category assigned to it that is stored in the array.
I know I need to use a tax query with the AND relation like in the following example:$args = array( 'post_type' => 'venue', 'posts_per_page' => -1, 'meta_key' => 'venue_menu_order', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'event_category', 'field' => 'slug', 'terms' => 'convention-without-exhibits', ), array( 'taxonomy' => 'event_category', 'field' => 'slug', 'terms' => 'convention-with-exhibits' ), ), );
The problem, however, is that I don’t want to hardcode the arrays that contain the taxonomy and term. I also know that I can’t loop through my array inside the $args array.
I did try this but it didn’t work because $tax_query is a string which doesn’t end up getting ran as php code ($event_types is the name of the array of Event Category slugs):
$tax_query =""; foreach($event_types as $event_type){ $tax_query .= "array( 'taxonomy' => 'event_category', 'field' => 'slug', 'terms' =>". $event_type." )"; } $args = array( 'post_type' => 'venue', 'posts_per_page' => -1, 'meta_key' => 'venue_menu_order', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'tax_query' => array( 'relation' => 'AND', $tax_query ), );
Any help or direction will be greatly appreciated. Thanks in advance.
- The topic ‘tax_query AND relation for same taxonomy’ is closed to new replies.