I have created foreach loop, but i want to show "No Post Found" if it returns no data

Viewed 266

I have create a code to display the events in list format. Everything is working Fine.But it show blank page if there is no data returned. So i want to simply show a message "No Events Found".

<?php
// declaring data           
global $post;
$all_events = tribe_get_events(array(
    'eventDisplay' => 'upcoming',
    'tag' => 'swiss',
    'posts_per_page' => 100
        ));
?>
<!-- fetching events based on upcoming and tags. -->
<?php foreach ($all_events as $post): ?>
    <?php setup_postdata($post); ?>
    <a href="<?php the_permalink(); ?>">
        <div class="col-md-12 event_col">
            <div class="col-md-4"><span>- <?php echo tribe_get_start_date($post->ID, false, 'dS M, Y | h:i a'); ?></span></div>
            <div class="col-md-4"><span><?php echo tribe_get_venue(); ?></span></div>
            <div class="col-md-4"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
        </div>
    </a>    
<?php endforeach; ?>
<?php wp_reset_query(); ?>
4 Answers

First you need to check whether the array is empty or not if the array is empty don't allow to get into the condition. Allow if the array is not empty and in that you can display the details and in else part you can display the message like no post found.

if(!empty($all_events))
{
  ##here you can enter code for display the detail like loop to display the details`
    foreach($all_events as $post) 
     { 
       ##DISPLAY POST DETAILS  
     }
}
else
{
## here you can show the message of no events found.
}

Check your $all_events variable:

if (!empty($all_events)) {
    foreach($all_events as $post) { 

    }
} else {
    echo 'No events';
}

Check $all_events has value or not

if(!empty($all_events)){
### do your code 
}else{
echo "No Post Found!";
}
}

Please check size of an array before starting with for each loop.

if(count($all_events) > 0){
    foreach($all_events as $post) {

    } 
} else {  
   echo "No Post Found!";
}

Hope it works!

Related