WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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


Then to check if there are actually any returned results:

    if ( $query->have_posts() ) :
       //Use a While loop to show the results
       //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>

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

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.

share|improve this answer
Thank you! That's definitely given me a push in the right direction. What I have at the moment is: while ( $the_query->have_posts() ) : $the_query->the_post();, then the stuff inside the loop, then endwhile;. Using your example above, what code would I use to set up the while loop instead? – Sarah Jan 10 '12 at 16:10
That's correct - just insert the 'while' code inside in between the 'if' and the 'else' above in mine :D. – Stephen Harris Jan 10 '12 at 16:49
Thank you so much - I've got it working! :-) – Sarah Jan 10 '12 at 17:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.