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?

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.

Alex bring a series of in-depth articles on search marketing and content management systems as well as troubleshooting tips to We Rock Your Web's collection. He is an avid tennis player, nature enthusiast, and hiker, and enjoys spending time with his wife, friends, and dogs, Bella and Lily.

76
Leave a Reply

avatar
newest oldest most voted
matt
Is the D7 code right? First, the using ” gives an error. Also my zen theme has

/ We hide the comments and links now so that we can render them later.
hide($content[‘comments’]);
hide($content[‘links’]);
print render($content);

I changed the use of “ to ‘, but no text in the body is displaying.

anonimous
Hi
Finally someone ‘properly’ helps the Drupal newbies and ‘old timers’ like me – yahoo!

Any help with Drupal 8?

I have wasted a week now.

Thanks in advance

Praveen
Did you find any ways to do it?
mayank bahuguna
please provide this solution for drupal8
Mikal Dickerson
Just thought I’d throw my .02 in on this as I just had a client on D7 ask me to find a way to place SimpleAd blocks inside certain content types. This will respond to anything you put in the block, so it can really be used for anything you want to inject into your content. Here’s my super ugly proof of concept that just uses the node.tpl.php and .info file for now. I can already see the “That’s not the Drupal Way” comments coming my way, but, again… Proof. Of. Concept.

First I added regions (instory1, instory2, instory3) to the .info file, then updated the node.tpl.php with this:

if ( !empty($node) && $node->type == ‘article’) {

// Which paragraphs should we place ads after?
$p1 = 3;
$p2 = 11;
$p3 = 18;

// Set the instory block variables
$instory1 = block_get_blocks_by_region(‘instory1’);
$instory2 = block_get_blocks_by_region(‘instory2’);
$instory3 = block_get_blocks_by_region(‘instory3’);

// Break out the body
$array = explode(“”, render($content[‘body’]));

// Find the last key of the array to make sure we don’t show ads if the content isn’t long enough

end($array);
$key = key($array);

// Now we need to reset the pointer back to the 0 index
reset($array);

// First ad placed
if ($p1 <= $key){
$array[$p1] = render($instory1). $array[$p1];
}

// Second ad placed
if ($p2 <= $key){
$array[$p2] = render($instory2). $array[$p2];
}

// Third ad placed
if ($p3 <= $key){
$array[$p3] = render($instory3). $array[$p3];
}

$content['body'] = implode("”, $array);
print render($content[‘body’]);

} // end the node type check

else {
print render($content[‘body’]);
}

matt
Doesn’t work
Asim
I’m having an issue. I’m using adsense module. I try to put ad in footer but it shows ad disable for this block.
How can I solve this?
cparkner01
Also is there anyway to make this show at let’s say the 4th tag? Would I just change the ” parts to read ”? so it would read:

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

Thanks.

cparkner
Really like the thought of being able to use this however when I follow the directions for my Drupal 6 site I get the following:
Parse error: syntax error, unexpected ‘/’ in /xxxxx/xxxxx/xxxxx/themes/garland/node.tpl.php on line 17

The code on line 17 is $arr = explode (“”, $content);
Not sure why it is not working, any help would be great.

song
I am an Adsense publisher and have been using it the past 2 years. I am happy with my earnings but I want to increase my earnings further. Can you suggest some other PPC programs which I can combine with Adsense to increase my earnings? I heard Infolinks works well with Adsense. Have you heard of them?

Anonymous
I reused an existing Adsense block (adsense_content), so I only had to add this in the node.tpl.php:

$arr = explode (“”, $node->content[‘body’][‘#value’]); // center content ads

if (count($arr) > 5) {

$arr[1] = $adsense_content . $arr[1];

$node->content[‘body’][‘#value’] = implode(“”, $arr);

}

I print the recycled Adsense block at the bottom of all pages, and only inject the block if there are more than 5 on the page.

Anonymous
Is there a way you can please, or anyone build a video presentation of this tutorial? That would be so helpful. Thank you.

Anonymous
How do you add Adsense ads into the middle of content on a Drupal site running Drupal 7? I can’t seem to find an example on how to do this.

Anonymous
Please give me a code that will work in Drupal 7.

Anonymous
I am still not able to get this to work in D7, even when I am doing what is written.

Anonymous
Under Drupal 7

1) There is no “template.tpl.php” file for the Drupal7 template I’m using (analytic). I just created one with the following code:

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

2) I’ve followed the rest of the tutorial and I receive this error. The module doesn’t show up inside the body text.

Warning: explode() expects parameter 2 to be string, array given in include() (line 25 of /home/xxxxx/public_html/yyyyyy/sites/all/themes/analytic/node.tpl.php).

Notice: Undefined variable: incontent in include() (line 26 of /home/xxxxx/public_html/yyyyyy/sites/all/themes/analytic/node.tpl.php).

Anonymous
I’m using the default d7 theme and did exactly as written but I get the following error:

Only variables can be passed by reference in node.tpl.php line 133

Anonymous
I am using the theme Arthemia for Drupal 7.

The node.tpl.php file does not have a point that says print $content, it has something more like this:


< ?php>
hide($content['terms']);
hide($content['links']);
hide($content['comments']);
print render($content);
?>
< ?php print render($content['links']); ?>< ?php print render($content['comments']); ?>

Help! getting the same error message, only variables can be passed by reference on the line of the original code (hide($content[terms],.

Anonymous
First of all I want to say think you for this tutorial.

I’m having a problem with styling the block in Drupal 6. The div class for the block is being given a generic tag (id=”block-block-10″ class=”clear-block block block-block”). I’ve got it working by modifying the code that goes in node.tpl.php to add an extra div tag but I’m thinking there is probably a better way to do this?

Manish
Thanks for the script, worked perfectly.

Anonymous
This article gives several ways to literally develop a content block template which will allow you to inject Google ads wherever you like. These directions are very detailed, along with the specific coding to use. You could literally copy and paste them right from the article into your drupal system and then immediately change the entire look of your pages.

Drupal is an excellent content management software program which helps to organize and structure your site. It is a great way to build and maintain a blog. Since the software code is all open source this is something which is constantly changing. Many different developers are building new tools and applications which daily add to the functionality and usefulness of this content management tool.

Of course, drupal is not right for everyone. However, I am hard pressed to even think of a type of web site which would not benefit from having better control over their content.

Anonymous
Selling the products of others is another excellent way to monetize a website. This is called affiliate marketing since the site owner actually becomes an affiliate of another website that sells a product which will appeal to their audience. Much has been written about how to do this and there are a number of theories and ideas which should be really considered before embarking on this method. Additionally, make sure you are promoting only products which are high quality and provide value to your visitors.

It should also be understood that using affiliate marketing is an excellent way to build a targeted list of prospects. Instead of actually sending visitors directly to the vendor web site, first send them to your site (or page, actually). On this page, you will have a headline which promises some kind of benefits that will be satisfied in a free report, video, audio or some other type of digital product. This is all done in exchange for their name and email address. The idea here is that if they go on to the vendor site and then leave without buying, they are forever lost to you as a possible sale. On the other hand, if you have their email address you can follow up with them through email and hopefully turn them into a customer later down the road.

Another option is to use advertising. The easiest way for this is to take advantage of the Adsense program and has Google display ads on your site. This is a usually a very good fit for many different sites, especially those whose goal is to provide good content for their visitors. Being able to insert these ads actually within some of your web pages is a really cool idea. This is especially true if your site is very specific and focused. You want to think hard about the keywords you will use in your content pages. Make sure that Google has a number of advertisers for those keywords. This will enable more relevant ads to be displayed, which will stimulate a number of clicks.

Anonymous
The Adsense program has been around for a long time, and this used to be a huge revenue generator for a wide variety of website owners. There were even site owners who tried to do what was affectionately called Adsense Arbitrage. This involved buying traffic through Google Adwords (the other side of the program, for advertisers) and then displaying Adsense ads which had a higher payout rate. Of course the key to this strategy was finding away to accurately identify which keywords were cheap and which were expensive. Not an easy process, since Google never reveals their prices. Additionally, they caught on to this procedure and implemented some policies which really put the end to this practice.

However, reading the article did make think that one of the biggest decisions a website owner needs to make is how to monetize their site. They could attempt to sell their own products. They could attempt to sell the products of others and make a commission on each sale. Or, they could use some type of advertising (whether through a system like Google or sell their own) and be compensated on the basis of either clicks or views.

Selling your own products is probably the ultimate goal for many site owners. This is unquestionably the most profitable, especially if you are selling information or something which you control the total supply and has a high profit margin. Obviously, information is just a digital file, which takes up no space and can be sold automatically time after time without anyone really even lifting a finger. Of course, many people consider developing their own product to be beyond their ability, especially if it involves them having to write. Although today an information product could just as easily be an audio or video file.

Anonymous
Kudos to you for really helping me to understand Drupal!

As I came across this article it reinforced a commitment that I had made to myself a while back, to learn more about how to use Drupal. In fact, I really did not know much about what Drupal actually was before reading this article. Possibly many other readers are having the same question?

Drupal, I discovered, is basically a content management system. This is similar to other services like WordPress and Blogger. However, it seems to be a lot more functional and powerful. This system is also open source, which means that anyone can view the source code and develop more modules and add functionality and features to the program. This is one of its strengths; the fact that things are always changing and becoming better and more powerful. A user looking to get started with Drupal could simply download the core program and then put it onto their server. From this point, they are free to add more modules, themes or translations.

This software is also very versatile. The point of this article was to emphasis how one of the more commonly modules, called Adsense Injector, works imperfectly (and how this can be improved). Unfortunately, since I am not a technical designer or Drupal user, I found the explanation slightly long-winded and a bit overly technical. Despite this, I am quite confident that there is enough help out there to guide anyone through the process of using Drupal effectively.

Another big take away I have from this article is the continuing importance of using Google Adsense as a method of monetizing sites. For the uninitiated, the Adsense program is a way that website owners can help to harness the power of online ads. By inserted a simple line of code into their site, this allows Google to display ads. Then, whenever any visitor actually clicks on one of those ads, the owner will make a small commission. The exact amount (and this amount is actually split between the owner and Google) is a mystery, but it depends on which keywords the ad(s) target and what the prevailing demand is for those words. The advertiser also wins because they place these ads on the basis of not being charged until someone clicks. Once this happens, the visitor is then taken directly to the site being advertised.

Anonymous
The D7 code is not working for most of us. Is there anyone who had made this work for him so as to share the code with all of us trying to make this work.

Anonymous
This is my solution for Drupal 7.10:

/** in 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;
}

/** in node.tpl.php **/

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

a web rocker
I’m trying to use the above code to get some Adsense in a custom content and keep getting the following error:

Notice: Undefined variable: output in mayo_preprocess_node() (line 292 of C:\xampp\htdocs\***\sites\all\themes\mayo\template.php).

Here is the code I’m using:

function mayo_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;

}

<?php

$array = explode(“”, $body[0][‘value’]);

$array[2] = $ad. $array[2];

$content[‘body’] = implode(“”, $array);

print render($content[‘body’]);

?>

I can get the Adsense ad to appear, but then none of my content appears. If I move the ‘node’ code below the render content statement, the ad show below the content, yet I still get the error above.

Could this be related to the Mayo theme? Any ideas?

Thanks in advance.

a web rocker
I’m also getting this error:

Notice: Undefined variable: output in mayo_preprocess_node() (line 291 of C:\xampp\htdocs\***\sites\all\themes\mayo\template.php).

Warning: explode() [function.explode]: Empty delimiter in include() (line 123 of C:\xampp\htdocs\***\sites\all\themes\mayo\templates\node–my_articles.tpl.php).

When I click on the [function.explode] link, I get this error in the content section:

The requested page “/***/function.explode” could not be found.

Is explode the wrong function for the latest Drupal 7 release?

Anonymous
In drupal 7 Zeropoint theme this is not working.

Anonymous
Has anyone had success with the Drupal 7 implementation ?

Anonymous
I am currently having an issue with the undefined variable hook in template.php

Anonymous
Thanks – this is just what I needed! For D6, I had to save the template file as ‘template.php’ rather than ‘template.tpl.php’ for it to work. Once that was done, it worked like a charm.