Drupal Insert Adsense to the middle of the content body

We will find various Drupal modules to inject the Adsense to our site content. However, they do not usually allow us to add the Adsense code to the middle of our content body. Here, I have included a simple tweak to the drupal code.

For this, we need to add some code to the file 'node.tpl.php' which is located inside our drupal themes folder. Open this file on your text editor and look for the line where the variable '$content' is printed. To be more specific, open 'node.tpl.php' and look for the code section below, on the file:

Now, we need to add a block of PHP code inside the div just before the PHP block displayed above. You can just copy and paste the code block below with no modification and it will just work fine for you.


What we've done here is pretty simple. First, we define a variable 'incontent' that holds the div block with class 'adsense_managed'. Note the class name here, as it is required to tweak our CSS later. We then put our Adsense Code inside this div.

We then check to make sure the ads aren't displayed on the front page. This check has been done to prevent our front page from getting cluttered with the ads.

And now for the main part, the three lines of code then, inserts our variable containing the adsense code within the content body after the third paragraph. You can simply change the array key '3' in the example above as desired to display the ad after respective paragraph.

Our Ad block containing div needs some CSS styling to blend it with the content body. You can simply insert the CSS code section below to your CSS file 'style.css' which is also located inside the Drupal themes folder.


/* styling the adsense code block */
.content .adsense_managed { float: left; margin-right: 5px; margin-bottom: 5px; }

The CSS code above floats the ad block to the left aligning the text content to its right. The margin are meant for maintaining a space between ad block and the content. You can set the float to 'right' and the ad block will be aligned to the right. If you do so, the 'margin-right' attribute should be changed to 'margin-left'.

This code has been tested to work correctly with the Drupal Version 6. I haven't checked it with other versions of Drupal.