WordPress: get posts within the loop
Posted by Dimitri | Oct 11th, 2010 | Filed under Programming
Get Odd/Even Posts
It is similar to the last page, however the if statement is going to be different. I will explain from the start, so there’s no need to go back to the previous page.
Create a variable that will count posts just before the WordPress Loop:
//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; ?>
Then, add the following if statement just before the end of the loop whenever you want the even posts:
//add this if statement <?php if($postCounter % 2 == 0) //get even posts { //Your code here, probably an advertisement. } ?> //WordPress Loop ends here <?php endwhile; ?>
Case you are looking for the odd posts, use this if statement instead:
//add this if statement <?php if($postCounter % 2 != 0) //get odd posts { //Your code here, probably an advertisement. } ?> //WordPress Loop ends here <?php endwhile; ?>
At the next page, how to get posts at a desired interval (Get every *insert number* posts).
Be the first to leave a comment!