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

I’ve used WP_Query to query and display events. In some cases, though, there are no events to be displayed and I’d like to display a friendly message when that happens instead of displaying nothing – but I’m not sure how to do this. If it was a mysql query I know I could use if(mysql_num_rows($result)==0) but I don’t think that works with WP_Query. Is there something else that will work?

Thanks very much for any help you can give me.
Sarah

Related posts

Leave a Reply

1 comment

  1. 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.