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;
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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