Using WP_Query – how to display something IF there are no results

So, let’s say $query is your WP_Query object. I.e.

    $query = new WP_Query($some_query_args );

Then you can set up ‘the loop’, by

    $query->get_posts();

Then to check if there are actually any returned results:

    if ( $query->have_posts() ) :
       //Use a While loop to show the results
    else:
       //No results, let's show a message instead. 
       //This is how WordPress' twentyeleven theme does it, but you can format it how you like:
        ?>

      <article id="post-0" class="post no-results not-found">
          <header class="entry-header"> 
              <h1 class="entry-title"><?php _e( 'Nothing Found', 'twentyeleven' ); ?></h1>
          </header>

          <div class="entry-content">
             <p><?php _e( 'Apologies, but no events were found.', 'twentyeleven' ); ?></p>
         </div>
    </article>
    <?php
    endif;

Keep in mind the logic, must be inside php tags, while the HTML markup must be outside.

Disclaimer: the syntax might not all be correct, I’ve not tested it. But check out index.php of the TwentyEleven to see what they do.

Leave a Comment