Skip to Content

Display Google AdSense After First Post in Drupal Using PHP

After researching for some time, I realised it is so simple to program PHP codes in Drupal to display Google Ads after a particular post (or node), for example, you may want to display Google Ads after the 3rd and 5th post, but not after every post. This is the tutorial for you!

There are terms to adhere to when publishing Google AdSense advertisement on websites, for example publishers are allowed only 3 content ads at any one single page view. Hence, after which, a blank space will be shown (in Mozilla Firefox) or a 404 Page Not Found error will be displayed (in Microsoft Internet Explorer 6) (I have not tried it in IE 7, so I am unable to comment on that).

(Get PHP code for Drupal to display Google Ads...)

In Drupal, you will only need to edit the "node.tpl.php" file in your specific theme folder, e.g.

/public_html/DRUPAL_SITE/themes/MY_THEME/node.tpl.php

For example, if you want to insert Google Ads after the 2nd and third article on the front page, insert the following code after the following line that says <?php print $content ?>:

<?php if(!$page&&($id==2||$id==3)): ?>
[INSERT ADSENSE CODE HERE]
<?php endif; ?>

PHP Code Explanation

  1. The first part of the "if" statement, (!$page), prompted a check to ensure that Drupal is not displaying a single node view.
  2. The second part of the statement, ($id==2||$id==3), tells the Drupal engine to display the AdSense code after the 2nd and 3rd post.

Users who are using earlier version of Drupal, i.e. 4.6.x and earlier, are to take note:

  • replace "$id" with "$seqid"

Drupal 4.7.x and later versions now uses $id instead, so you should have no problem.

Check out the screenshot above to have a clear view of the outcome; in my case, I have chosen to place it only after the second post.

Hope this tutorial helps!

Trackback URL for this post:

http://www.neohide.com/trackback/226

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options