0

Can we count the WordPress loop and store it in a variable?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $post_id = get_the_ID(); ?>
    <?php get_template_part('content','home'); ?>
       some code to be executed
<?php endwhile; ?>
<?php endif; ?>

what I want is that for every 5 posts fetched ceratin code should be executed(example newsletter) → That means within the loop for every 5h, 10th, 15th, ____________ infinite posts(5n, n>=1) the code should be executed.

2

$wp_query->current_post is the build-in loop counter, starting with 0 zero for the first post in the loop.

so the line some code to be executed could translate to:

<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>

3
  • sir, it worked, but can you help me in explaining this part → current_post % 5 == 0 Sep 23 '17 at 3:41
  • 1
    It’s checking if the remainder of current_post divided by 5 is 0. Sep 23 '17 at 4:50
  • OK! Thanks. It is a kind of pure maths but in coding form. The maths that we do in GRE or GMAT. Sep 23 '17 at 15:06
1

PLease check this code snippet

 <?php  $i=0; 
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <?php $post_id = get_the_ID(); ?>
    if($i%5 == 0)
    {\\code to be executed}
    <?php get_template_part('content','home'); ?>
       some code to be executed
<?php $i++;endwhile;  ?>
<?php endif; ?>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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