Want to Place Drupal Adsense in the Middle of Your Content?

To sustain this free service, we receive affiliate commissions via some of our links. This doesn’t affect rankings. Our review process.

Drupal comes with many handy modules, not the least of which are the Adsense and Adsense Injector modules – which let you control the look, feel, and placement of your Adsense ads within your Drupal pages. The problem? The Adsense injector, while having the right intentions, isn’t quite to the level where it will allow you to “inject” ads into the middle of your content. For the more technically inclined – in your theme’s node.tpl.php file, the print $content statement prints the actual body of your content.

Adsense Injector Doesn’t Quite Inject…Yet

Ideally, the Adsense Injector module would allow you to inject Adsense ads into the middle of your body content (within the content printed by $content). However, at this point it only allows injection before and after $content, in other words, before and after your body content. The solution is to tweak your template files so you can inject an ad block into the middle of your Drupal content following a specified number of paragraphs (you determine this number and can change it to your liking).

The Ad Module Injects, But Only One Ad Per Content Type

The ad module (advertising module for Drupal 5 and up) offers a variety of ad type options (external, HTML, banner, etc), and is setup for injections. In fact, it lets you specify precisely after which paragraph you’d like your ad snippet “injected.” The drawback is that you can only inject one snippet per content type instance (for example, inject one ad block per “page” content type, specifying it to appear after every 2nd paragraph, for example).

So, without further ado, we release our template-based method of inserting Adsense ads into the middle of your content.

How To Insert Adsense Ads In The Middle Of Drupal Content

We’re going to show you how to insert your ads right into the middle of your content – not at the beginning or the end. The implementation of this tweak is going to depend on the version of Drupal you’re using. In this article, we’re going to cover Drupal 8.x, Drupal 7.xDrupal 6.x, and even Drupal 5.x for those of you with vintage taste ;-). If you’re using another version, simply post below and we’ll do our best to accommodate your request.

Inserting Adsense Into Content – Drupal 8.x

Unfortunately finding a working solution for Drupal 8 in the vein of one of the solutions below has been taxing at best. The good news is there are some modules that will do the heavy lifting for you. Give them a try and let us know in the comments how your experience was:

  • Google Adsense Integration – lets you build Adsense blocks that auto-update (ie. you change the Adsense script in one place, and it updates wherever you’ve placed the block). Combine with the block field module using this tutorial to get Adsense ads to display within your content.
  • Try WordPress – I’m not trying to be facetious here, but let’s face it – this article was originally published all the way back in 2009, that’s a decade ago! And Drupal hasn’t made inserting Adsense into content any easier. That’s because the Drupal platform was not built for publishers. WordPress was. As you can see by this site, we made the switch over half a decade ago and haven’t looked back.

Inserting Adsense Into Content – Drupal 7.x

Thanks to one of our web rockin’ readers for sharing this Drupal 7 solution with us. Please let us know if this also works for you!

template.php

function THEME_preprocess_node(&$variables) {

//load your adblock
$adblock = block_load(‘block’, ‘1’);
$output .= drupal-render(_block_get_renderable_array(_block_render_blocks(array($adblock))));
$variables[‘ad’] = $output;

node.tpl.php

$array = explode("", $body[0]['value']);
$array[1] = $ad. $array[1];
$content['body'] = implode("", $array);
print render($content['body']);

The Drupal 7 code is very similar to the code for Drupal 6, with a couple minor tweaks. Follow the Drupal 6 instructions below, but use this Drupal 7 specific code instead in your theme’s template.php file (new code in bold):

function theme_name_preprocess_node(&$vars, $hook) {
// don’t load region in teaser view
if ($hook == ‘node’ && !$vars[‘teaser’]) {
$vars[‘incontent’] = theme(‘block’, array(‘title’=>’incontent’));
}
}

Inserting Adsense Into Content – Drupal 6.x

For Drupal 6.x, the process is a bit simpler than in Drupal 5.x. First, you’ll want to define a new region for your Adsense “in body” code in your theme’s .info file. Beneath your defined regions, add a line that defines your new region (if there are no regions, make sure you redefine all your regions (left, right, header, etc.) or they will disappear):

regions[left] = Left
regions[right] = Right
regions[header] = Header
regions[incontent] = In Content

Next, we expose this region variable to your node template file. Simply add the following to your theme’s template.php file:

function theme_name_preprocess_node(&$vars, $hook) {
// don’t load region in teaser view
if ($hook == ‘node’ && !$vars[‘teaser’]) {
$vars[‘incontent’] = theme(‘blocks’, ‘incontent’);
}
}

Make sure you replace theme_name with the folder (directory) name of your theme. The preprocess_node statement tells the function that we’re addressing your node.tpl.php file.

Finally, the last step is to insert code in your node.tpl.php file that will actually insert the new ad region into the middle of your content:

<?php
$arr = explode (“</p>”, $content); // center content ads
$arr[2] = $incontent . $arr[2];
$content = implode(“</p>”, $arr);
?>

Important: This code snippet needs to be inserted before

<?php
print $content
?>

What this does is simply insert the content of your incontent block after the second paragraph printed by your node.tpl.php file. So in effect, by assigning an Adsense block to your incontent block, your ads will be inserted after the second paragraph within your body content. To adjust the number of paragraphs used for insertion, simply adjust the 2 in the second line of the example above.

The only remaining step, to make this all work, is to actually assign an Adsense block to your new incontent region. Before you do this, you need to clear the theme cache, which will cause the changes you made to your .info file (the newly defined regions) to load. To do so, simply visit your theme select/ configuration page (via Administer -> Site Building -> Themes). If for some reason you get the message, when visiting your block page, that your blocks were disabled since they were assigned to invalid regions – don’t panic, simply confirm that you have all your regions in place in your .info theme file, and then clear your theme cache as described above.

Inserting Adsense Into Content – Drupal 5.x

If you’re using Drupal 5.x, you’ll need to edit the following files to have Adsense inserted after 2 paragraphs of your body content (simply change the number 2 if you wish to adjust the number of paragraphs following which ads are inserted).

First, we’ll add a block region to your template, which will control the placement of your “in content” ads. To do so, simply modify the template.tpl.php file within your theme directory, adding the following:

/* in body ad placement */
function template_name_regions() {
return array(
‘right’ => t(‘right sidebar’),
‘left’ => t(‘left sidebar’),
‘content’ => t(‘content’),
‘header’ => t(‘header’),
‘footer’ => t(‘footer’),
incontent‘ => t(‘in content’)
);
}

function _phptemplate_variables($hook, $vars) {
// region distributor
$variables = array();
// don’t load region in teaser view
if ($hook == ‘node’ && !$vars[‘teaser’]) {
// load region content via block assignment
foreach (array(‘incontent‘) as $region) {
$variables[$region] = theme(‘blocks’, $region);
}
}
return $variables;
return $vars;
}

You’ll notice that we added an ‘incontent‘ region. When you administer your blocks, you’ll be able to select this new region from the block placement drop-down menu. It’s important that you replace template_name in the above example with the folder name (directory name) of your theme.

Next, you’ll want to add the code that actually inserts your Adsense ads into this newly created block. Add the following at the top of your node.tpl.php file:

<?php
$arr = explode (“</p>”, $content); // center content ads
$arr[2] = $incontent . $arr[2];
$content = implode(“</p>”, $arr);
?>

What this does is simply insert the content of your incontent block after the second paragraph printed by your node.tpl.php file. So in effect, by assigning an Adsense block to your incontent block, your ads will be inserted after the second paragraph within your body content. To adjust the number of paragraphs used for insertion, simply adjust the 2 in the second line of the example above.

The only remaining step, to make this all work, is to actually assign an Adsense block to your new incontent region. Once you’ve done that, and the above code is in place, your ads should automatically be inserted in the middle of your Drupal content.

Clear Your Cache

If your ads aren’t showing up as intended, visit Administer -> Site Configuration -> Performance and clear your entire cache. Once you’ve done that, and the above code is in place, your ads should automatically be inserted in the middle of your Drupal content.

Styling The Placement Of Your ‘In Content’ Ad Block

By default, your “In Content” Adsense block will cause all text to fall beneath it. The ad region will integrate even better with your content if the text falls around it, ie. to the right or left of it. To accomplish this, simply add the following line to your theme’s style.css file:

/* adsense */
.content .adsense_managed { float: left; margin-right: 1em; margin-bottom: 1em }

In this example, your adsense block is floated to the left, so your content body’s text will fall to the right of it, instead of beneath it. We also added in a little margin to give some space between the ad text and your body text, so the two don’t appear to run together. Finally, if you wish to float the ad block to the left instead, simply change the float attribute to float: right, and adjust your margin to margin-left.

You’ll notice that your Adsense block configuration allows a setting ad alignment, but all this does is align your text (ie. justify it via the CSS declaration text-align: left (or right, or center))- it will not cause your entire ad block to float to the left (or right) of your text.

Were You Able To Get This To Work On Your Site?

About The Author:

Alex has been involved on the business side of the internet since the early 2000's. He holds both a Management Science degree from the University of California at San Diego as well as a Computer Science degree from NJIT.

We Rock Your Web had its roots back in 2004 as the tech blog for a web design and development company Alex founded that has grown and evolved into the parent company of We Rock Your Web.

While his foundation is rooted in web development, his expertise today lies in content and digital marketing, SEO, organic and paid search, analytics, and publishing. Alex is an avid tennis player, nature enthusiast, and hiker, and enjoys spending time with his wife, friends, and dogs.

Disclaimer: This website contains reviews, opinions and information regarding products and services manufactured or provided by third parties. We are not responsible in any way for such products and services, and nothing contained here should be construed as a guarantee of the functionality, utility, safety or reliability of any product or services reviewed or discussed. Please follow the directions provided by the manufacturer or service provider when using any product or service reviewed or discussed on this website.

Subscribe
Notify of
76 Comments
Inline Feedbacks
View all comments