Thursday, September 29, 2011

Drupal adsense in content

This tip will show you how to insert your ads in the middle of your content with Drupal 6. Drupal 6 has many modules with lots of functions to do things, but if you can get to do things without installing a new module is much better!
So, if you want to insert adsense or any other javascript based ads in the middle of you content, in between your paragraphs, you can do it with a little bit of php.

1. Open your active theme folder, usually in /sites/all/themes/my_active_theme

2. Open the file page.tlp.php please do a backup of this file first

3. Search the line:   <?php print $content ?> and insert this code right before

// Show ads when user is not logged in
// Show ads in the middle of content
$adsBlock='<script type="text/javascript">PLACE YOUR JAVASCRIPT CODE HERE</script>';
$arr = explode ("</p>", $content); // center content ads insert ads after first paragraph
$arr[1] = $adsBlock . $arr[1];
$content = implode("</p>", $arr);
This will show ads in the middle of your content right after the first paragraph, if you want to show your ads after the secod paragraph change this line
$arr[1] = $adsBlock . $arr[1];
$arr[2] = $adsBlock . $arr[2];

This code insert your ads after the first or second paragraph so it will appear in the middle of your article.
The ads will show once even if it is on the teaser view, it will only appear in the first post, so you won't have too many ads appearing.
And finally to make it work, clear the site cache to see changes. Now your ads appear in the middle of  content
All this is simply done without installing another Drupal module you only have to copy the code and adapt it a little bit to your needs.
In fact Drupal adsense module does not inject the ads in the middle of content but before or after the content, so here you've got a very easy way to do it, it works like a charm!


Post a Comment

Your opinion is very appreciated, thank you!