Added AdSense (Part II)

Last week I looked at the option of adding sponsored links via AdSense to this site. So far I am getting around 5 bucks from the clicks. Not too bad I guess, but at the same time it is far from covering my Internet bandwidth. An interesting exercise nevertheless, as it was my very first attempt on milking some cash from an Internet website.

I read Nicole Simon's article on ProBlogger this morning, and he looked at the option of separating your daily readers and visitors, when you display your ads. I happen to have quite a few daily readers who track me through services like Bloglines and FOCUSer.net's recent updates, and I like to hide ads for them. At the same time, I am also getting a few hundred visitors landed here via Google, Yahoo!, MSN Search and others, searching for some particular information - these are the people I especially like to target the ads with.

So Simon's solution is - only show ads to the blog posts that are a few days old. A great idea! A few minutes of PHP hacking, here's a list of rules that governs whether AdSense will be shown:

  • Post is at least 7 days old & not in some specific categories.

  • Referrer is either Google, Yahoo! or MSN Search.

I am now showing ads in two places - at the end of blog entry, and at the top of the index page. I have PHP/WordPress code that looks like this:

  <?php if (show_ads()) { ?>
  <script type="text/javascript"><!--
  google_ad_client = ...
  //--></script>
  <script type="text/javascript" 
      src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
  </script>
  <?php } ?>

And my PHP function that checks whether ads needs to be shown:

<?php
function show_ads() {
    global $posts;
    $referer = $_SERVER['HTTP_REFERER'];
    if (isset($referer)) {
        if (preg_match('/^http:\/\/(www)?\.?google.*/i', $referer) ||
            preg_match('/^http:\/\/search\.yahoo.*/i', $referer) ||
            preg_match('/^http:\/\/search\.msn.*/i', $referer))
        {
            return true;
        }
    }                                                                                                                   
    if (is_single()) {
        $t = $posts[0]->post_date;
        $t = mktime(substr($t, 11, 2), substr($t, 14, 2), substr($t, 17, 2),
                    substr($t, 5, 2), substr($t, 8, 2), substr($t, 0, 4));
        if ((time() - $t) > 604800) {
            if (!in_category(21) && !in_category(3) && 
                !in_category(40) && !in_category(14)) 
            {
                return true;
            }
        }
    }

    return false;
}
?>

It checked against 4 different categories (mainly christianity-related) and will not show ads if someone browses these blog posts. I know I should have made it into a plugin, but was too lazy to do so and the code is really very site-specific. I am just putting them here hoping it might be useful for some.