Placing Adsense After Your First WordPress Post

Google Adsense is a great way to make some money off of your blog, and by placing your code in a couple of key places in your template files, you can have it automatically displayed on all of your blog posts. One thing to keep in mind though is that you can only show 3 ads per page, any more than that and in most browsers an empty space will be left, which is to some extent ok, but in other browsers it can appear as a broken iframe or image. While an empty space isn’t ideal, it can be acceptable, a broken section on your site really isn’t.

It’s for this reason that most people will set up their template to only display Adsense code on the first post shown on each page where multiple posts are displayed. For example on your index page, category pages, tag pages and archive pages.

So to ensure that your Adsense code only displays once you need a way to make sure that when WordPress loops through each post, there is some way for it to figure out whether or not it’s the first post. Joe over at joehayes.org has written a great post about doing this.

Somewhere before the start of the WordPress loop, you need a base way to count. Joe has done this by placing the following code:

<?php $count = 1; ?>

Before the WordPress loop which starts off with:

<?php if (have_posts())

Then inside the content section of the loop which starts off with:

<?php the_content

You need to decide whereabouts you are going to put your Adsense code. Paste it in somewhere, this could be before or after the post content, or after the meta information, or anywhere else that be suit your particular template.

Now, just before the start of your Adsense code you need a way to check the number of posts. We’ll use some PHP to check the $count number that we set earlier.

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

This checks to make sure it is still 1. If it is, then your Adsense code will be displayed. If not then it won’t be.

Directly after your Adsense code we then need a way to make sure that the other posts don’t also appear as number 1.

<?php endif; $count++; ?>

This section of PHP tells WordPress to add 1 to the counter. So the next time WordPress runs through the loop, it will be a 2 instead, and it will go 1 higher for each post, so only the first post will appear as 1, thus only the first post will show the Adsense code.

It’s pretty simple but it does the trick very well!

If you wanted to display 2 or 3 ads, one on each of the first 2 or 3 pages, you could simply change the PHP around a little bit.

<?php if ($count <= 3) : ?>

The above snippet for example tells WordPress that if the count number is 3 or lower, than it should display the Adsense code with only 2 minor changes to the original code.

Be Sociable, Share!

Leave a Reply