cqde
cqde

Reputation: 705

WordPress Loop Display Content if Have Posts

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

I'm using the loop to pull a few custom posts to display on the site. I have a designated <div> to hold the posts. I've run into the problem when there are no posts to be pulled, the div box still displays with no content in it. How would I insert the code of my div container within the "if" statement so that the div is only created if there are posts?

Upvotes: 0

Views: 9722

Answers (3)

samkitson
samkitson

Reputation: 184

Try the following code snippet:

<?php if (have_posts()) { ?>

  <div>

<?php } ?>

<?php while (have_posts()) : the_post(); ?>

  ...

<?php endwhile; ?>

<?php if (have_posts()) { ?>

  </div>

<?php } ?>

<?php endif; ?>

I hope this helps!

Upvotes: 1

fuxia
fuxia

Reputation: 63576

Create a 404.php for your theme and drop the if (have_posts()) completely. You can start the loop with the while statement, and WordPress will use the 404.php if there are no posts.

Upvotes: -2

Richard M
Richard M

Reputation: 14543

<?php if (have_posts()) : ?>
  <div>
    <?php while (have_posts()) : the_post(); ?>
      …
    <?php endwhile; ?> 
  </div>
<?php endif; ?>

You may find the documentation on PHP's alternative syntax useful

Upvotes: 5

Related Questions