WordPress: get posts within the loop
Posted by Dimitri | Oct 11th, 2010 | Filed under Programming
This post will explain how to get posts at the WordPress loop, so you can place code (probably advertisement code) after a specific post (first, second, third) or at intervals (e.g.: every 3 posts).
Before starting, it is a good idea to create a backup copy of your theme’s index.php file, just in case anything goes wrong.
This is a five page post, so here is the page index:
- Get the first post
- Get the 2nd, 3rd or any other post
- Get odd/even posts
- Get post intervals
- Final considerations
Let’s begin by finding where to place the code. That’s why we need to find the WordPress Loop in the index.php file.
Identifying the WordPress Loop
After making the backup copy of index.php, you will have to locate the beginning and end of the WordPress Loop.
The beginning of the loop should look like this line:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
The end, should look like this:
<?php endwhile; ?>
After that, follow one of these instructions.
Get First Post
To run a block of code after the first post, create a boolean variable before the WordPress Loop:
//add this line <?php $firstPost=true; ?> //WordPress Loop starts here <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
Then, add the following if statement just before the end of the loop:
//add this if statement <?php if($firstPost && !is_paged()) //get the first post on the first page { //Your code here, probably an advertisement. } ?> //WordPress Loop ends here <?php endwhile; ?>
And that’s all there is to it. The next page explains how to get the 2nd, 3rd or any other post.
Be the first to leave a comment!