How To: Conditional Adsense Ads Display in WordPress

I get a decent number of emails asking how I show Google Adsense ads on older WordPress posts on my blog.

Although there may be plugins for WordPress that allow you to display Google Adsense ads based on the age of a post, there weren't any when I needed them years ago. So… here is the php code that I use to show adsense ads on older posts:


<?php /* Check if post and age for adsense */ if (is_single()) { ?>
<!-- insert google ad based on post age KD -->
<?php
$days_since = floor((date('U') - get_the_time('U')) / 86400);
if($days_since >= 20) {
echo '~~~~~~~~~~~~~~'; }
?><?php } ?>

(Click here to see an older post that has Adsense ads – both in the sidebar and after the post)

In a nutshell, this php code determines if the page being displayed is a single entry, if wordpress post is at least 20 days old and — if both conditions are met — inserts the Google Adesnse code.

To use this on your wordpress blog, simply replace ~~~~~~~~~~~~~~ in the code above with your adsense javascript code and insert the code into your templates where you would have the ads appear. On my blog, I paste this code into a text widget in my sidebar, as well as in the post-footer.

If you want to expand on the idea to showing adsense conditionally, you can modify this code fragment to work with a variety of WordPress conditional tags.

Share on FacebookTweet about this on TwitterShare on LinkedInEmail this to someone

One thought on “How To: Conditional Adsense Ads Display in WordPress”

Comments are closed.