wp query – Filter for each loop when WP_Query has no posts to show


I’m looking for a way to filter the results of a for each loop based on a custom taxonomy when the WP_Query inside the for each loop has no results.

More specific, I have an Event post type with a custom taxonomy. On a page I want to display all taxonomies but only if that taxonomy has events where the event data is in the future. The event date is a custom field (ACF).

Th following code shows all taxonomies even when the WP_Query has no results / when there are now events for that taxonomy in the future.

<?php // Get all the categories
$categories = get_terms( 'soort-event');

foreach ( $categories as $category ):

// Chech if event start date is in the future  
$meta_query = array(
                'key'     => 'datum_event',
                'value'   => date('Ymd'),
                'type'    => 'DATE',
                'compare' => '>',
// Get all events
$events = new WP_Query(
            'post_type'       => 'events',
            'orderby'         => 'meta_value_num',
            'order'           => 'ASC',
            'posts_per_page'  => '3',  
            'tax_query' => array(
                'taxonomy'  => 'soort-event',
                'terms'     =>  $category,
                'field'     => 'term_id'
            'meta_query'      => $meta_query
<section class="events">      

<h2><?php // Show the event taxonomy name
   echo $category->name;?></h2>

<div class="row events">

<?php // Show the event details
while ($events->have_posts()) : $events->the_post(); ?>
<div class="event-meta">
    <?php the_title();?>


<?php // End  event loop 


<?php // end for each taxonomy loop

Is there a way to filter the results and hide the ’empty’ taxonomies which don’t have an Event where the event date is in the future?

NielsPilon 3 weeks 2021-03-22T06:52:28-05:00 0 Answers 0 views 0

Leave an answer