Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

In a previous post I talked about placing Google AdSense ads into FlatPress themes without violating Google policy. In this post I will talk about a better way to achieve the same effect: basically this comes down to making sure that a single ad unit is only shown once per page.

The net effect is like this:
betteradsense.png


The ad is shown once after the first post and not shown again after any other posts. It's possible to place any content using this approach exactly once per page.


To achieve this, a small amount of PHP is required to be embedded into the entry-default.tpl file in the theme. This code will keep track of how many times the entry template has been looped through.

So here's the code:

One of the readers, Cam, noted that you need {literal} tags when pasting your AdSense code in, this is due to the JavaScript that's used, thanks Cam, good catch!


{php}
global $adshown;
if (!isset($adshown)) {
{/php}
{literal}
*** YOUR ADSENSE CONTENT HERE ***
{/literal}
{php}
$adshown = true;
}
{/php}


When the template is used the first time on a page, this code looks for the '$adshown' variable, if it is not set, it displays the AdSense content and sets the variable to true. On any subsequent passes through the enter-default.tpl, the variable will be set, so the AdSense content will not be displayed. The trick here is to use the 'global' keyword to make sure that the variable is preserved between each time the entry template is used.

It's also possible to extend this to display the content multiple times by changing the $adshown to an integer, incrementing it's count in the if statement and adding a check on the to the if statement to see if the counter is over a certain amount.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.