WordPress: get posts within the loop
Posted by Dimitri | Oct 11th, 2010 | Filed under Programming
Get post intervals
Again, you will have to create a variable to count posts:
//add this line <?php $postCounter = 0; ?> //WordPress Loop starts here <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
And increment this variable inside the loop:
//insert ++$postCounter; after the_post(); <?php if (have_posts()) : while (have_posts()) : the_post(); ++$postCounter; ?>
Now, for the if statement, we are going to compare if the rest of the division of the desired interval equals to zero. Let’s say that we want to display an advertisement every 3 posts:
//add this if statement <?php if($postCounter % 3 == 0) //get every 3 posts { //Your code here, probably an advertisement. } ?> //WordPress Loop ends here <?php endwhile; ?>
If we wanted to place ads, the above code would display the same type every 3 posts. To display different ads, at different intervals try this:
//add this if statement <?php if($postCounter % 3 == 0) //get every 3 posts { //Your code here, probably an advertisement. } if($postCounter % 5 == 0) //get every 5 posts { //Your other code here. } ?> //WordPress Loop ends here <?php endwhile; ?>
The last page explains some terms used in these examples and some final considerations.
Be the first to leave a comment!