Drupal: How To Display Ads To Non-Members Only

Trevor from Basketball Help sent me an email asking how I am able to display Adsense ads to non-members without displaying them to registered members of the site. I remember when I first wanted to show ads to non-members only, it was difficult to figure out because this is not really a feature that is built into Drupal. It requires a tiny bit of simple PHP coding and I had to do quite a bit of searching before I was able to finally figure out how to do it – so this is a really good question for anyone new to using Drupal.

Before I get into how I was able to do this, I want to point out that Khalid Baheyeldin has created a Drupal module that makes displaying Adsense ads to only selected roles much easier. You can find Khalid’s Adsense Module at the Drupal.org website. If I ever have time, I fully intend on removing all my custom PHP coding and replacing it with Khalid’s module.

How I did it:
OK – so this is how I do it, the hard way. If you want to show your Adsense ads in one of the sidebars, create a new block, and make sure the input-format is set to PHP. In the block-body, insert this bit of PHP code:


<?php

global $user;
if (!$user->uid){
?>
ADSENSE (or anything) GOES HERE

<?php
}
?>

Enable your block, and that’s it.

To display your Adsense ads to only non-members on a regular page, use the same code anywhere on your page. Just make sure the input-format is set to PHP.

See? Easy! Even if you do it the hard-way!

How I display Adsense ads only on forum-posts:
Since this is kinda related, and because this was also difficult for me to figure-out, I decided I’d post it here too.

To display a block (of anything) only in your Drupal-Forum areas create your block as usual. In the Page Specific Visibility Settings field, select:
Show if the following PHP code returns TRUE (PHP-mode, experts only).
and put the following code in the “Pages” field:


<?php
if (arg(0) == 'node') {
$node = node_load(array('nid' => arg(1)));
return $node->type == 'forum';
}
?>

Now this block will be displayed only on forum posts. I use this technique to display an Adsense Skyscraper and Auction Ads on all of my forum pages but I combine it with the technique for only displaying to non-registered visitors.

If you try either of these techniques and have questions or trouble, post a comment and I’ll do my best to help.

Leave a Reply

Your email address will not be published.