Get the FULL version

WordPress: get posts within the loop

Get the 2nd, 3rd or any other post

To get the the 2nd, 3rd or any other post number, 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:

//add this if statement
<?php if($postCounter == 2 && !is_paged()) //get the second post on the first page
{
    //Your code here, probably an advertisement.
} ?>
//WordPress Loop ends here
<?php endwhile; ?>

Note that, by checking if $postCounter has the same value as the number 2, it returns the 2nd post. This way, if you want the third post, just use the number 3 instead:

if($postCounter == 3 && !is_paged())

It is possible to get the first post using this method by replacing the number inside the if statement with the number 1. But why create a counter if it is going to count up to 1?

The following page explains how to get odd and even posts.

Pages: 1 2 3 4 5

Be the first to leave a comment!

Leave a Comment

Post Comments RSS