Garry Conn

How to Display Google AdSense Ads to Search Engine Traffic Only

Back a few years ago when I was using WordPress I used a plugin called, Who Sees Ads. The plugin worked great and did it's job well; however, just like WordPress I felt like the plugin -as for most WordPress plugins- was much more complicated than it needed to be in order to get the job done!

In my opinion, to do something as simple as displaying ads to visitors who come from search engines or displaying no ads for everyone else shouldn't take an engineering level of mastermind coding. It's a simple IF and THEN situation. It's not like we're trying to write a script that will automatically make your laptop grow wings and take a trip to the moon!

That overall sums up my opinion about WordPress and WP Plugins. It has all become far too complicated for doing the simple task of web publishing. Anyway, all that said, here's a practical and simple PHP code that will allow you to display Google AdSense ads -or other types of banner ads and text links- to visitors coming in from search engines and then display nothing else to everyone else.

<?php
$referrer 
$_SERVER['HTTP_REFERER'];
$my_domain "example.com";
$search_engines "google|yahoo|bing|altavista|digg";
$pattern "((http(s)?://)(\w+?\.)?(?!{$my_domain})({$search_engines}))";
if (
preg_match("/{$search_engines}/i"$referrer) != false) {
    echo <<<END
    <script type="text/javascript"><!--
    google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
    /* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
    google_ad_slot = "xxxxxxxxxxxxxx";
    google_ad_width = xxx;
    google_ad_height = xxx;
    //-->
    </script>
    <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script>
END;
} else {
    
// Show something to visitors not referred by a search engine
}
?>

You can download a copy of this code here.

Feel free to drop me a comment below if you have any problems adding this code to your website or feel like you can improve the code in any way. The code can also be used in WordPress themes too if you would rather not use the Who Sees Ads plugin. Special thanks to the contributors at StackOverflow for helping me with this code.