There are a number of plugins you can use to add Google Adsense to your blog. Unfortunately, most of them have very little flexibility when it comes to the positioning of the ads. But fret not; there are a few hacks you can use to hard code the Adsense code to your blog. These hacks are applied to your theme.
The obvious place to have your Adsense is on your home page. In this post, we’ll look at inserting Adsense on your hope page. This would be in the loop in the index.php page. As you can guess, it will also be applied to other pages that use the loop, namely the various archives pages.
Let’s begin:
Open the index.php file of your theme and find the line <?php if ( have_posts() ) : ?> and add the following just before this line:
<?php
$postnum = 1;
$showadsense1 = n1;
$showadsense2 = n2;
$showadsense3 = n3;
?>
Just change n1, n2, and n3 to whatever posts you want the Adsense to appear after. So if you want it to appear after the 1st, 4th and 8th posts, just change it to 1, 4 and 8 respectively. Also, if you only want one Adsense unit in the loop, discard the lines: $showadsense2 = n2; and $showadsense3 = n3;.
Next, scroll down to the line <?php endwhile; ?> and add the following code just before it:
<?php if ($postnum == $showadsense1) {
echo '
Your adsense code
';
} ?>
<?php if ($postnum == $showadsense2) {
echo '
Your adsense code
';
} ?>
<?php if ($postnum == $showadsense3) {
echo '
Your adsense code
';
} ?>
<?php $postnum++; ?>
Obviously, you need to replace Your adsense code with your adsense code. If you only want one Adsense unit, discard the second and third bits of php code.
That’s it, just upload the altered index.php page to your theme folder and your Adsense will be enabled.
Maybe you don’t want Adsense to appear on archives pages that have only one post as that might look MFAish? Not a problem, just show Adsense from the second post onward. Alternatively, you can filter out archive pages that have a post count of 1 by using $wp_query->post_count in the first bit of php code that inserts your Adsense code. In other words, you’d replace the code that you inserted before the line <?php endwhile; ?> with the following:
<?php if ($postnum == $showadsense1) {
if (($wp_query->post_count) == 1) {
echo ' ' ; }
else {
echo '
Your adsense code
';
}
} ?>
<?php if ($postnum == $showadsense2) {
echo '
Your adsense code
';
} ?>
≶?php if ($postnum == $showadsense3) {
echo '
Your adsense code
';
} ?>
<?php $postnum++; ?>
There’s no need to alter the second and third iterations of the Adsense code as these won’t appear anyway if there’s only one post.
In our next post we’ll look at creating a short code to insert Adsense in your posts.

Leave a reply