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

| Views: 8085
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

Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...