Check if WordPress loop has posts

I have a custom loop with posts which are added from the custom meta field checkbox. Only if the checkbox is checked, then the post is being added to the loop. I have a container that holds that loop. What i want to do is to check if that loop got any posts and if it is empty – just hide that container. Because otherwise when the loop is empty the container is remaining on the page:

<div>
  <ul>
  </ul>
</div>

This is the loop:

Read More
<?php 
/* Slider ------- */
$slider = new WP_Query('showposts=-1');
if ( $slider->have_posts() ):
?>  
<div>
    <ul>
    <?php while ( $slider->have_posts() ) : $slider->the_post(); ?>
        <?php if ( get_post_meta($post->ID, "mf_homeslider", true) == 'slider_on' ){ // Check if post was added to slider ?>
        <li>
        <?php if (has_post_thumbnail()) {  ?>
            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail('large'); ?> 
            </a>
        <?php } ?>
            <div>
                <?php get_template_part('includes/post_meta'); ?>
                <h2>
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </h2>
            </div>
        </li>
        <?php } ?>
    <?php endwhile; ?>
    </ul>
</div>
<?php 
endif;
wp_reset_query();
?>

Thank you in advance for your help.

Related posts

Leave a Reply

1 comment

  1. You should filter your query by the custom field (see details here), it could also improve performance (an SQL condition vs. a while-if loop). After that, have_posts() returns whether the loop contains any posts.

    So instead of

    $slider = new WP_Query('showposts=-1');
    

    use

    $slider = new WP_Query(array(
        'meta_key' => 'mf_homeslider',
        'meta_value' => 'slider_on',
        'posts_per_page' => -1)
    );
    

    and there’s no further need for if ( get_post_meta(...

    (showposts is deprecated, use posts_per_page instead).

    Note: you are mixing braces and if-endif style, the latter would be much readable when nesting.