According to Google AdSense Program Policies you are allowed to add up to three ad content units in a page. If you have over 10 posts in a page and you wish to insert Google ads between them, you may need to specify the position of each advertisement (for instance, the first is after the 3rd post, the second after the 7th post and the last one is after the 10th post) and make sure that the limit of 3 ad content units is not exceeded. In this short tutorial I will teach you how you can do that. The code can be applied in every page where posts are shown including the index, the archive, the tags and the search results.
I will work with the index.php file from WordPress Default Theme. The code from other themes is pretty much the same so you just need to pay attention to the details 😉
First, let’s setup the ads. We will use an array that will store the advertisements’ codes. Find the code:
<?php while (have_posts()) : the_post(); ?>
and replace it with:
<?php /* Key = Position of the Ad Value = The AdSense Banner Code */ $advertisements = array('3' => '<!-- adsense ad code 1 here -->', '6' => '<!-- adsense ad code 2 here -->', '9' => '<!-- adsense ad code 3 here -->'); $i = 1; while (have_posts()) : the_post(); ?>
As you can see each banner code has a key assigned. For example, the second element has the key 6. We will use this value to show the banner after the 6th post on the page (in the case there are at least six results).
Now, find the line:
<?php endwhile; ?>
and change it with:
<?php if(array_key_exists($i, $advertisements)) { // you can add custom HTML code here echo $advertisements[$i]; } $i++; endwhile; ?>
How it works?
As you can see I have declared the variable $i that auto increments inside the while statement. The $i number is incremented at the ending of each loop. Here we use array_key_exists() to see if there is any key equal with $i. For instance at the 9th loop the value of $i would be nine and will be verified if there is any key equal with 9 in the $advertisements array. If it is, the advertisement is shown.
Note: You can keep as many elements you want in the array. You can add for instance additional banners beside the ones from Google AdSense.
That’s all! If you have any questions please post them! Happy coding 😀