I’m trying to display certain events on my site’s front page using wp-query. It’s working, but not fully the way I need. (Admittedly, though I have lots of experience with wp-query, I’ve never really used tax_query. That may be where I’m getting tripped up.)
I have several Event Categories in use. On the front page, I want to display all “sticky” events except those from three categories (call these “exclude-1,” “exclude-2,” and “exclude-3”). However, if an event has both one of the excluded categories and one of the included (or not excluded) categories, I want it to be displayed.
Here’s an example of how I would do this with regular WP Posts:
<?php
$frontposts_args = array(
'post_type' => 'post',
'post__in'=>get_option('sticky_posts'),
'post_status' => 'publish',
'nopaging' => false,
'order' => 'DESC',
'orderby' => 'date',
'cat' => '-35,-220,-145',
'posts_per_page' => 3,
)
?>
<?php $frontposts = new WP_Query( $frontposts_args ); ?>
<?php if ( $frontposts->have_posts() ) : ?>
<?php while ( $frontposts->have_posts() ) : $frontposts->the_post(); ?>
In this case, posts that are categorized with categories (by ID) 35, 220, and 145 aren’t displayed. Except if I add another category to a post (one that isn’t explicitly excluded), then the post appears. Huzzah!
With Event Categories, I tried doing it like this:
<?php
$upcoming_args = array(
'post_type' => 'event',
'post__in'=>get_option('sticky_posts'),
'suppress_filters' => false,
'posts_per_page' => 4,
'event_end_after' => 'yesterday',
'showpastevents' => false,
'orderby' => 'eventstart',
'order' => 'ASC',
'post_status' => 'publish',
'tax_query' => array (
array(
'taxonomy' => 'event-category',
'terms' => array('exclude-1', 'exclude-2', 'exclude-3'),
'field' => 'slug',
'operator' => 'NOT IN',
)
),
'nopaging' => false,
)
?>
<?php $upcoming = new WP_Query( $upcoming_args ); ?>
<?php if ( $upcoming->have_posts() ) : ?>
<?php while ( $upcoming->have_posts() ) : $upcoming->the_post(); ?>
The problem: When I do this, it excludes any events with the excluded categories, even those that also have other categories assigned. Is the solution to include all those other (non-excluded) categories, rather than excluding the three I want to exclude? Or maybe there’s just a better way to construct my query?