How to insert ad codes after first, second or nth post?

How to insert ad codes after first, second or nth post?

In this post I’ll show you how to insert ad codes (anything else) after first, second or nth post on homepage/archive pages.

Lets admit that most of us blog for money more or less. You are probably implementing Google adsense, or joining some affiliate programs, or staring your own products. If you can create a promo box after first, second, or nth post on the homepage, archive pages, you are in a better position to earn more.

In order to achieve this, just follow me and make some small coding.

Let’s  take homepage (index.php) for example. The same techniques apply to archive pages (category.php, tag.php, author.php, archive.php, and even search.php) as well.

Open your index.php and find the codes to display the loop. If you are using TwentyThirteen theme, you can find this:

The piece of codes may be different on different themes, just make sure to find the loop, always starting from while and ending with endwhile.

Method one: $wp_query

Now just paste following codes just before endwhile.

In above codes, current_post == 1 means after 2nd post as it starts from 0. So lets say you want to add after 5th post, the code should be current_post == 4.

Now the whole codes look something like following:

Method two: variable $count

There is an alternative for this, just for your choice.

The difference is we have used a variable $count here.

(update on Nov 18, 2014) You have to modify the theme by using above method. I have found another way (maybe better) posted by scribu to  do the same thing.

Now your turn. Do you have better solutions? Or do you have any trouble when implementing this? Feel free to leave a comment below.

Save

Author: Leo

My name is Leo who's behind this blog. I've been working with wordpress since 2010. I'll write about themes, plugins, tutorials and all about wordpress here. Hope you find it useful!

2 thoughts on “How to insert ad codes after first, second or nth post?”

Leave a Reply

Your email address will not be published. Required fields are marked *