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

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
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

Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...