The question:
Having formulated my $query for a custom taxonomy on a page template, how would I ask if a specific term has posts?
$args = array(
'post_type' => 'exhibitions',
'tax_query' => array(
array(
'taxonomy' => 'exhibition',
'field' => 'slug'
),
)
);
$query = new WP_Query($args);
Assuming I’m on the right track, a verbal description of the sort of conditional statements I’m looking for would be:
if the $query taxonomy term ‘current’ have posts, do something;
elseif the $query taxonomy term ‘upcoming’ have posts, do something else;
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
I’m not sure what you exactly need, but normally, by default, get_terms
returns only terms that actually have posts assigned to them
$terms = get_terms( 'exhibition' );
var_dump( $terms );
Apart from this, I really do not know what you exactly need
Method 2
It sounds like you want has_term()
. Something like:
Feed your query an array of terms:
$args = array(
'post_type' => 'exhibitions',
'tax_query' => array(
array(
'taxonomy' => 'exhibition',
'field' => 'slug',
'terms' => array(
'current',
'upcoming',
),
),
)
);
$query = new WP_Query($args);
Then loop over it multiple times:
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
if (has_term('current','exhibition')) {
// stuff
}
}
}
$query->rewind_posts();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
if (has_term('upcoming','exhibition')) {
// stuff
}
}
}
$query->rewind_posts();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0