CodeinWP CodeinWP

Inject Custom Ad Blocks Between Paragraphs in WordPress

How to Inject Custom Ad Blocks Between Paragraphs in Older WordPress PostsIt’s common nowadays for bloggers to monetize their blogs through the use of strategically-placed ad blocks. BuySellAds ad blocks are the most popular in the web design community. You’ll sometimes also see AdSense ads placed at the top of articles or in other spots.

It becomes a bit of a challenge, however, to include ads in older posts. Nobody wants to go through and edit each post, adding customized code manually, which could be quite time consuming.

The best way to do this is to put the ad code in your single.php page, outside of the function that displays the post. Unfortunately, with this method, the ads are limited in location to either the top or bottom of the article. In this tutorial, I’m going to describe some JavaScript that I wrote that will dynamically embed a custom ad block between paragraphs in a chosen set of WordPress posts.

The JavaScript/jQuery Code

Here is the code that accomplishes this:

$(function() {

  myDivCollection = document.getElementsByTagName("div");
  
  for (i=0;i<myDivCollection.length;i++) {
    if (myDivCollection[i].id.indexOf("post-")!= -1) {
      var myChildren = myDivCollection[i].childNodes;
    }
  }
  
  var counter = 0;

  for (i=0;i<myChildren.length;i++) {
    if (myChildren[i].nodeType != 3) {
      counter += 1;
      if (counter == 5) {
        var newDiv = document.createElement("div");
        newDiv.innerHTML = "<p id=\"adblock\"></p>";
        var myTarget = myChildren[i];
        myTarget.parentNode.insertBefore(newDiv, myChildren[i]);
        $("#adblock").load('../adblock.html');
        break;
      }
    }
  }

});

<

p>Here is a description of the code shown above (I realize it could be simplified with jQuery, but I just feel more comfortable coding most of it raw):

  • The entire code is wrapped in the usual “document ready” handler, thus you need the jQuery library included before this code block
  • Lines 3-9 collect all <div> elements, and loop through them, looking for the one that has an id that contains the string “post-“. This identifies that element as the one that contains the post content. When that’s found, its child nodes are added to another collection.
  • Line 11 defines a “counter” that will be used in the subsequent loop.
  • In the next loop, we iterate through the “children” of the previously identified post container. Line 14 ensures that the elements we loop through are not text nodes, which some browsers count as part of the DOM tree. With each non-text node found, the counter is incremented (line 15).
  • Lines 16-22 are run when the 5th element is found. The first five child elements (not counting grandchildren) in my WordPress posts will normally be the <h2>, followed by the paragraph with post info (date, author, etc.), then three content paragraphs. This might be different for your blog, so you can adjust the number accordingly. You could also write some code to target the first subheading, and inject the code before that element.
  • Line 17 creates a <div> element, and line 18 adds content to it, which inludes a new ID’d element, so we can target it later.
  • After line 20 adds the element to the DOM tree using the insertBefore method, we use an Ajax call (using jQuery syntax) to inject our code block into the previously created ID’d element.
  • Finally, to prevent the loop from continuing past child #5, we use the break command.

If you change the number 5 in line 16, that will allow you to customize where you want the ad block to appear. Of course, you can’t go too high with that number, because if there are only 3 or 4 paragraphs in the post, then the loop would never include the code (which isn’t bad, I suppose).

To make sure it works, you have to confirm the location of your ad block file. In my case, since my post URLs don’t include categories, I would just include my code in the root directory of my website, and the “../” appended before the file location ensures that it’s found.

Only Run the Code on “Single Post” Pages

You only want this code to run on when a single post is shown. So, you would use the following in your header.php file:

<?php if ( is_single() ) { ?>
<script type="text/javascript" src="/js/ad-block.js"></script>
<?php } ?>

Doesn’t Work with AdSense or BuySellAds

It would be great if this code worked with AdSense or BuySellAds, but unfortunately it seems that AdSense and BSA ads cannot be injected into the page in this manner via Ajax (or in iframes). At least I couldn’t get it to work, but maybe I’m doing something wrong. I’ll have to investigate further. I’m awaiting a reply from BSA to see what they have to say about it.

UPDATE: I’ve received a response from Todd at BSA, and he says that there is no current support for dynamically injecting ad blocks via Ajax, but it’s something that will be supported in the future.

So while this solution has some merit, it might only be practical for a custom ad block or other “feature” box that you want to include between paragraphs in certain posts.

Restrict it to Older Posts

You can use the following value in your header.php file, to run the code only on posts that are older than (for example) 7 days, or some other amount of time:

$current_post_date = $wp_query->post->post_date;

The line of code above obtains the value of the publication date of the currently viewed single post page. You can then use that value to create a function that compares that date to the current date, then you can run the JavaScript only when the post date matches the qualifications you set.

Another way you can identify only older posts (and probably the easiest way) is to look for the ID of the post, using this value:

$current_post_id = $wp_query->post->ID;

Then you can do something like this:

<?php if ( is_single() && $wp_query->post->ID < 300) { ?>
<script type="text/javascript" src="/js/ad-block.js"></script>
<?php } ?>

If the "older" posts begin at number 300 (going backwards), then that would ensure that the code only runs on those, so this seems to be much easier than comparing the dates.

Any Suggestions?

I would love to hear some suggestions to how this code can be improved in order to allow for AdSense or BuySellAds to be used, and there may be some drawbacks that I haven't mentioned here.

Also, I know there are many WordPress plugins that allow for ad management, but from the research I did, I couldn't find one that allows you to include the ad block in older posts, and in the middle of a post (as opposed to at the top or bottom, which is easy to do manually anyhow). So, if anyone knows of a good ad manager that offers these options, then that would be a bonus. (Although I do like the simplicity of a simple JavaScript file that accomplishes this task, instead of a bloated plugin.)

UPDATE: I found a plugin that (according to the description on the plugin page) is able to include AdSense in the middle of the post, and allows it to be limited to older posts. It's called WhyDoWork AdSense Plugin.

To demonstrate the code, I've modified it to run on a single post on my website. I'm using it to include a "related link" feature, so you can see how it works. You'll see it using the demo link below — it's the gray-outlined box that appears after paragraph two in the article.

THE DEMO BUTTON BELOW links to another tutorial that shows the script in action. (See paragraph above)

13 Responses

  1. Jonathan says:

    This is awesome this will be a great plus for any site wordpress is so easy to work with .with all the new plug in why would you use any thing else. Thank for great info on your site.

  2. That is a really nice right up on blog advertising, it will definitely come in handy. thanks!

  3. Bryan says:

    “View Demo” button links to another tutorial –> http://www.impressivewebs.com/cnn-beveled-navigation-buttons-css/

    Is there a demo page?

    • That’s the demo page. The box that appears in that article at the top of the article (after 2 paragraphs) demonstrates the code shown here in this article. I explained that in the last paragraph in this article, but I guess I’ll put it in bold for the “scan” readers. :)

      Thanks.

  4. Atul Kash says:

    I find this technique much better than the one where people place an advertisement after the end of the first paragraph.
    This way the reader has to look at the advertisement. It will be my first priority as soon as I get some time. Great article

  5. Jauhari says:

    It’s will be good if support AdSense and BSA ;)

  6. Zabava says:

    Nice post thank you for sharing! :-)

  7. ASAD ULLAH says:

    its coooooool. thanks for this lovely post.

  8. Neil says:

    This looks really good (even if I haven’t got it working yet).
    Have you removed the demo now? It doesn’t seem to be visible on single posts.

    Also – if you are using Ajax to call the adblock file, does that mean it can sit on a different server?
    thanks

    • Neil,

      So sorry about that. I did a big overhaul to my site’s code recently, to optimize for speed, and it seems I took that code out and didn’t realize it. I probably thought it was something for testing, and disabled it. Thanks for pointing this out, as I would not have noticed otherwise.

      Anyways, I’ve restored it. If you click the “view demo” button, you’ll be taken to another article on this site, and the ad block appears dynamically near the top, but ONLY on that article.

      Regarding your second question, no, AdSense and other ad networks don’t allow the ad blocks to be injected via Ajax. Also, Ajax as a technology does not permit this, except when using certain methods. See this article for an explanation on Ajax’s limitations with cross-domain requests.

      • Neil says:

        Thanks for putting that back in Louis. I’ll try and get it working on my site now. I may have more luck on a live site than on my local machine. I think I may have the path to the adblock set up wrongly.
        And thanks for your reply re Ajax.

        • No problem. Keep in mind (as I mentioned in the article) that this doesn’t work with Adsense (and maybe not with any ad network code), because they don’t seem to want you to inject code in this manner. Probably because of some security concerns, or the ability to manipulate impressions or something.

  9. Lee H says:

    I struggle with javascript so take what I have to say with a grain of salt. I use lazyload to load all my adsense code after the pages load. You place a div with a class of whatever you want with a variation of the adsense code needed to display the ad. LazyLoadad (I believe is the name) searches for that div and rewrites the code to become javascript and the ad is loaded when it’s done.
    It might be helpful to study what those fellas did and it might turn on a lightbulb for you?

    Good luck :)

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).