PHP: Disabling Adsense on All Posts Within the Last Week

I’ve always disliked having Adsense on my blog, but like many bloggers, I really need to recoup the costs of hosting my site. And since I personally dislike slow loading websites, I’ve tried to keep my website running as fast as possible with a quality hosting provider like MediaTemple… which isn’t exactly the cheapest hosting out there.

I’ve decided that a nice compromise to reward the faithful readers of my blog is to disable the ads on blog posts newer than one week. This means that if you are reading my blog via a feed link, or even from a current link posted on a social site like dzone, you won’t have to see any annoying ads on the page. At all.

So how to go about this? Turns out it’s pretty simple… It took me a minute of googling to remember how to subtract days from a date object in PHP.

This gives you a date object from exactly one week ago:

$lastweek = time() - (7 * 24 * 60 * 60);

Then, all I needed was to open up the single.php file in my theme directory, and change my adsense deluxe code to look like this:

<?
$lastweek = time() - (7 * 24 * 60 * 60);
if(get_the_time(’U') < $lastweek){
    adsense_deluxe_ads(’largerect’);
}
?>

If you aren’t using Adsense Deluxe, you can always just substitute your own ad code in there. Also, if you want to set a longer or shorter date range, just substitute the 7 for whatever amount of days you want.

Another note, if you are using WP-Cache to cache your content, is that the ads won’t start showing up after a week unless you whack your cache every so often. Not a huge deal, but something to keep in mind.

And just like that, no more ugly ads on “current” blog posts.

Leave a Reply