WordPress.org

Forums

[resolved] Block Google Adsense on individual posts (3 posts)

  1. stephennewton
    Member
    Posted 6 years ago #

    Hi
    Like many people I use Google AdSense, with ads in the blog template. Some pages on my blog promote gambling. This perfectly legal here in the UK, but Google have changed the terms of their program -- http://adsense.blogspot.com/2007/06/policy-updates-and-its-not-even.html -- so that Google Ads should not appear on this pages. I need a simple way of marking individual blog posts where Google Ads should not appear.
    Any ideas?
    Thanks

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    You say that you have the ads inserted directly into the template. So what it sounds like you need is some way to flag a post and prevent the ads from displaying if that post is one that would be displayed on the page.

    You can flag a post using a custom field, or tags, or perhaps even by using keywords in the post content.

    Figuring out if that post will be displayed is trickier. Essentially, you need to run through the Loop and look for your flag in all the posts, then call rewind_posts() to rewind the loop and show the posts.

    So you use something like this in your header.php:

    <?php
    while (have_posts()) {
    the_post();
    // check for your flag here, somehow and set $adsense;
    // false means block the adsense, true means show it
    $adsense = false;
    }
    rewind_posts();
    ?>

    This is to set your flag. Then, everywhere you use adsense, you surround it with this:

    <?php if ($adsense) { ?>
    adsense code here
    <?php } // end adsense code ?>

    Then it won't display unless you've set $adsense to true.

    Now, how do we check? Well, you could set a custom field on those posts. Say, add a "noadsense" key to them (with any value, doesn't matter, "1" would work). Then your check in the header.php would be like this:

    <?php
    while (have_posts()) {
    the_post();
    $custom=get_post_custom();
    if (array_key_exists('noadsense',$custom)) {
    $adsense = false;
    break;
    }
    else $adsense=true;
    }
    rewind_posts();
    ?>

    And there you have it.

  3. stephennewton
    Member
    Posted 6 years ago #

    Perfect. Thank you very much.

Topic Closed

This topic has been closed to new replies.

About this Topic