Counting in the wordpress loop

Rate this post

Can I ask a little help please.

I have a WordPress loop of posts. And I have some full width banner images that I want to show after every 4th post to break the content up.

So the code below works perfectly for the first 12 posts, but I can’t work out how to multiply past the 12 iteration.

What I’d like to happen is this;

Banner One shown AFTER post 4 + every 12 after that (16, 28 and on…).

Banner Two shown AFTER post 8 + every 12 after that (20, 32 and on…).

Banner Three shown AFTER post 12 + every 12 after that (24, 36 and on…).

Would really appreciate some advice on the math required.

With thanks Dan.

<div class="tile-flex">
    <?php $counter = 0; ?>

    <?php if (have_posts()) { while (have_posts()) { $counter++; the_post(); ?>
            <!-- Tile Grid -->
            <div class="tile-grid">
                <!-- Catalogue Tiles | WordPress Loop -->
                <div class="tile">
                    <?php get_template_part('includes-tile/custom-memorial', 'tile'); ?>

   <?php if ($counter === 4) { ?>
        <!-- Full Width Panel -->
        <div class="full-width-experimental-panel">
            <?php get_template_part('includes-page-panel/fullwidth','memorial-panel-one'); ?>
   <?php } ?>
   <?php if ($counter === 8) { ?>
         <!-- Full Width Panel -->
         <div class="full-width-experimental-panel">
             <?php get_template_part('includes-page-panel/fullwidth','memorial-panel-two'); ?>
   <?php } ?>
   <?php if ($counter === 12) { ?>
         <!-- Full Width Panel -->
         <div class="full-width-experimental-panel">
             <?php get_template_part('includes-page-panel/fullwidth','memorial-panel-three'); ?>
   <?php } ?>

   <?php }} ?>



I would look at using the modulo function.

This will tell you whether a number is a multiple of something, rather than exactly equal to it.

For example:

36 % 12 returns a result of 0 because the modulo shows the remainder of the first number being divided by the second number. If there is no remainder, then the first number is evenly divisible by the second, so you know it is a multiple of that number.

So you might say something like:

<?php if ($counter % 12 == 0) { 
 //do stuff

This will execute code in the brackets if $counter is a multiple of 12.

Leave a Reply

Your email address will not be published.

Back to top button