Wordpress – Place something after only the most recent post

I often receive emails from people who ask questions around the topic of not being overly repetitive. A good example is the social icons everyone places at the end of their posts – as you’ll see, after careful analytics studying, I noticed that they weren’t really doing my home page any justice and sacrificing a couple hundred hits for the space is going to pay off. Anyway, back to the topic at hand, how do you place something only after the first post?

I guess a good example to work with would be a banner advert, so let’s take a look at that. Each post in Wordpress has a unique ID assigned to it, which means you can identify the first, 10th, 100th or last post quite easily. In this case, we want to identify the most recent post.

The first thing you’ll need to do is add a counter to your Wordpress loop, what this will do is basically count all the posts as it loops through them. You can do this by modifying your loop to look like this..

<?php while (have_posts()) : the_post(); $counter++; ?>

The next step is to tell the loop what to do when we reach the most recent post. This is done simply with an IF statement, like so..

<?php if ($counter <= 1) : ?>

<?php endif ?>

Inside the IF statement, is where you’ll insert your banner code. Putting it all together will look something along these lines:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $counter++; ?>

<?php if ($counter <= 1) : ?>
<a href=”#”><img src=”banner.jpg”></a>
<?php endif ?>

<?php endwhile; ?>

Nice and easy, yet so powerful!

About the author:




Christopher is the founder of iMod - Most of his time is spent building websites and pushing the limits with Search Engine Optimization. You can follow him on Twitter @ChristopherM

Chris M has written: 4156 posts.

Have your say..



 By checking this box, you'll receive email updates when someone comments on this thread :)




Back to top ^
home | about | advertise | contact | links | forum

Afrigator myScoop