Show or Prevent Adsense ads on Selected Posts in WordPress

There are a lot of  customizations available, if you are using Google Adsense to monetize your blog and using WordPress as the blogging platform.  You can use plugins to show or prevent Adsense ads anywhere in your blog posts, but if you need to prevent Adsense Ads on selected posts or pages, here is a quick tutorial.

Let’s say you write a weekly round up post where you do not want to show any the ads but would want the ads to appear in all other posts. This can be achieved using WordPress custom fields and a simple conditional check as described below:

Prevent Adsense Ads on Selected Posts using Custom Fields

1. Open the corresponding file of your Wordepress theme where you have the code of your Adsense unit. This can be your single.php file for single posts, index.php for home page or may be sidebar.php for the sidebar.

2. Paste the following code where you would want the ads to appear or hide:

<?php $ads_display = get_post_meta($post->ID, “ads”, true);
if ($ads_display == “no”){ ?>
<!– no ads –>
<?php } else { ?>
Enter ad unit code
<?php } ?>

3. Replace “Enter ad unit code” with the actual code of your Adsense unit, save the file and upload it back to your themes folder.

4. Log in to WordPress administration area and create a new post. Assign a custom field with the name as “ads” and choose the value as Yes or No.

5. If you choose “Yes” the ads will appear as usual while choosing No will hide the Adsense ad on that selected post.

Note: All the earlier posts will display the ad units as usual but you can still use the custom field on older posts and hide or show the ads.

This method is good for hiding ads in selected posts or pages but it has one disadvantage. You have to choose the custom field for each and every post and set the value to Yes or no. To solve this, you can use a category and prevent the ads from appearing in all posts of that category.

Hide Adsense Ads on Posts of A Particular Category

This method is simple, just create a category and whenever you want to hide the ads on a particular post – assign the post this category. Here are the steps:

Open the corresponding file of your WordPress theme and paste the following code wherever you want the ads to appear

<?php if (in_category(‘categoryid’)) { ?>
<!– no ads –>
<?php } else { ?>
Enter ad unit code
<?php } ?>

Remember to replace “categoryid with the actual ID of the caegory. Multiple categories work out just fine.

More tweaks:

1. Show Adsense ads on longer posts using word count.
2. Show Adsense ads only to Search engine visitors.

Don't miss the Free Book

101 websites for getting things done - an informative book which will make you more productive and efficient. Subscribe to get it for free.