0

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.

1
  • 2
    Either reset the counter yourself, or make use of the mod operator (%) if (($counter %3) == 0) Commented Sep 16, 2013 at 13:40

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: If you use modulo (recommended), you never need to reset the counter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.