Bram Vanroy
Bram Vanroy

Reputation: 28437

Insert a div every three items in the wordpress loop (php)

I am trying to add an image after every three posts in the wordpress loop. Here's the loop:

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

  <?php /* The loop */ ?>
  <?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content', get_post_format() ); ?>
  <?php endwhile; ?>

  <?php twentythirteen_paging_nav(); ?>

<?php else : ?>
  <?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

My guess would be to insert a counter, but I'm not sure about the placement. My guess.

<?php if ( have_posts() ) : ?>
  <?php $counter = 0; ?>     
  <?php /* The loop */ ?>
  <?php while ( have_posts() ) : the_post(); ?>
  <?php $counter++; ?>
    <?php get_template_part( 'content', get_post_format() ); ?>
  <?php if ($counter == 3) echo '<img src="url-to-img.jpg" alt="img">'; ?>
  <?php endwhile; ?>

  <?php twentythirteen_paging_nav(); ?>

<?php else : ?>
  <?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

But even if this would work (not tested), the counter should reset after the image has been inserted. How should you do that?

Summary: insert an image after every three posts.

Upvotes: 0

Views: 1423

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25384

Sounds like you need the modulo operator. Instead of doing if ($counter == 3), which checks if the counter is three, you should do if ($counter % 3 == 0), which checks whether $counter is evenly divisible by three.

Upvotes: 3

Related Questions