Show AdSense to Google Search visitors in WordPress

I put AdSense ads on my WordPress plugin pages since the donation button wasn’t exactly raking in the dough. I inserted my AdSense code straight into these pages’ content. Looking through some of my stats I noticed a few of my posts got lots of hits from Google Search that would be good for ads. I didn’t want to show ads to my friends and normal readers so I went looking for a simple solution.

I borrowed some of the code used in this post, One template function checks the referrer, if it returns true then you display your AdSense code in your post template, single.php in my case. This goes in your functions.php:

function scratch99_fromasearchengine(){
$SE = array('/search?', '', '', 'search.', '', '', '/search/', '.yahoo.');
foreach ($SE as $source) {
if (strpos($ref,$source)!==false) return true;
return false;

and this goes in your post template where you want the ads to be displayed:

<?php if (function_exists('scratch99_fromasearchengine')) {
if (scratch99_fromasearchengine()) { ?>
<?php } } ?>

And that’s it. Visitors coming in from Google and some other search engines will have whatever ad you want displayed. There are plugins that will do this all for you, but this is simple enough to build straight into your theme. The only downside is if you are using caching, but odds are only your older posts are going to be getting hits from Google. If a page happened to get cached with the AdSense code inserted then everyone will see the ads. Not really a big deal to me, but just something to be aware of.

One Reply to “Show AdSense to Google Search visitors in WordPress”

Comments are closed.