WordPress, if no results from loop, don’t show header

I am using WP_Query to loop through a custom post type in wordpress. My loop looks like this:

<div class="bigRedStrip">
    <h2>Available Now!</h2>
</div>

<ul>
    <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?>

    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

            <li>
             loop stuff here
            </li>

    <?php endwhile; ?>
</ul>

As you can see, before the loop there is a header that says “Available Now!”. I want to reformat the loop so if there are no posts returned, then the div containing the title (div class bigRedStrip) will not be displayed. I have tried a number of potential solutions, but the problem I keep running into, is that all of these “solutions” require putting the <div class="bigRedStrip"> inside the loop, which results in the header repeating for every returned post. The idea is to have the header only displayed once. Any ideas how I can accomplish this?

Related posts

Leave a Reply

2 comments

  1. You only need to pull the things a bit apart. First of all run the query:

    <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?>
    

    Then check if there is something:

    <?php if ($loop->have_posts()) { ?>
    
    <div class="bigRedStrip">
        <h2>Available Now!</h2>
    </div>
    
    ...
    

    And if so, just iterate over the posts:

    ...
    
    <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    
                <li>
                 loop stuff here
                </li>
    
        <?php endwhile; ?>
    </ul>
    
    <?php } ?>
    
  2. <?php $loop = new WP_Query( array( 'post_type' => 'films', 'post_child' => 0, 'posts_per_page' => 8,'orderby' => 'date', 'order' => 'ASC', 'film-categories' => 'blu-ray' ) ); ?>
    <?php if ($loop->have_posts()){
    <div class="bigRedStrip">
            <h2>Available Now!</h2>
    </div>
    
    <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    
            <li>
             loop stuff here
            </li>
    
        <?php endwhile; ?>
    </ul>
    <?php } ?>