Page 1 of 1

WordPress – Inject Ads into your Posts

WordPress – Inject Ads into your Posts
   0

Unfortunately, when running a website, some kind of income is needed to cover the hosting expenses. Often this is done by placing ads.
Like most other websites, even Tweaking4All has to resort to placing ads, although I’d rather have zero adds, but donations alone isn’t covering the costs.

The downside of ads, besides being annoying at times, is that they only generate revenue when placed strategically, so folks will click on them (hint!).

Now, I will not claim to be the right person to ask where you should place ads, but in my opinion there are 3 reasonably “good” locations.
At the beginning and end of an article, and … in the smack middle of an article.

In this article, I’ll show you how you can automatically have an ad placed in your content, on the fly. With this code you can place an ad just before the nth <H2> tag. We will not use a plugin, and the code is simply added to the “functions.php” file of your theme.




Placing Ads in your WordPress Posts

So, first of all, I wanted to avoid using a shortcode.
First of all, half the time I forget to add them to my post, and second of all, well, I prefer to add as less shortcodes as possible – just in case articles have to move to another setup, or a shortcode no longer works, or ad rules change, etc. Just keep the post as clean as we can.

This example will take the content of a post, just before displaying it on your website, but without modifying your post content in the database, and insert you “ad code”.

For this we break the content of the post with the PHP statement “explode“, which takes a delimiter to determine where to break the text into pieces. These pieces are stored in an array. Note that it removes the delimiter from the text in the array, so we have to add it back into the text again.

Since I want to place the ad just before the second <H2>  tag, I’ll use “<h2” as the delimiter.
Yes, I took only part of the <H2> tag, since there might be additional information inside the <H2> tag, for example:

<h2 id="1234">Chapter X</h2>

With my code, it will look for the 2nd occurrence of “<h2” and place the ad right before that tag.
You can modify this to fit your needs, by changing the value of $ChapterCount you can decide before which tag occurrence you’d like to see the ad:

$ChapterCount = 2;

A creative programmer can modify the code of course, to place ads in multiple spots, or in the middle (for example, divide the “count($content)” by 2 – and try to find the sweet spot).

For placing multiple ads, just repeat the “if” statement in the “for” loop multiple times.

Please note that if there are less than two “<h2″‘s in the content, in this example code, NO ad will be placed.

PHP Code to insert an Ad into your Post

Feel free to use and/or modify the code below …

It will add a filter for “the_content” to inject the Ad, which makes it work automatically.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function t4a_insert_ad_in_content($content)
{
    if ((!is_singular('post')) || (strpos($content, '<h2') === FALSE) ) {  return $content; }

    $ChapterCount = 2; // Enter the chapter number, which you'd like an add in front of

    $content = explode("<h2", $content);

    $new_content = '';
   
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $ChapterCount) {
            $new_content .= 'your advertisement code goes here';
        }
       
        if($i>0) {
          $new_content.= "<h2".$content[$i];
        } else {
          $new_content.= $content[$i];
        }
    }
   
    return $new_content;
}
add_filter('the_content', 't4a_insert_ad_in_content');

 

Google AdSense thoughts

Since I use Google Adsense, I can place only 3 ads per page.

To make sure I do not exceed this limitation, I create a global variable ($GLOBALS['AddCounter'] ) and a function that returns the Google Adsense code.

In that function I first check if $GLOBALS['AddCounter'] is set, and already exists.
If not, then set it to “1”, otherwise I increase it by “1”.

If the value exceed 3 (limit of Google Adsense) then it will just return nothing, else it will return the code for a Google Ad – just in case I call that function more than 3 times by accident.


1
2
3
4
5
6
7
8
9
10
11
12
function t4a_generate_google_ad_code() {
...
if (!isset($GLOBALS['AddCounter'])) {
  $GLOBALS['AddCounter']=1;
} else {
  $GLOBALS['AddCounter']=$GLOBALS['AddCounter']+1;
}

if ($GLOBALS['AddCounter']>3) { return; }
... // your ad code generation goes here
return $adcode;
}

If you’d use a function like that as well, then your ad-injection code might look like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function t4a_insert_ad_in_content($content)
{
    if ((!is_singular('post')) || (strpos($content, '<h2') === FALSE) ) {  return $content; }

    $ChapterCount = 2; // Enter the chapter number, which you'd like an add in front of

    $content = explode("<h2", $content);

    $new_content = '';
   
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $ChapterCount) {
            $new_content .= t4a_generate_google_ad_code; // call functie for generating ad code
        }
       
        if($i>0) {
          $new_content.= "<h2".$content[$i];
        } else {
          $new_content.= $content[$i];
        }
    }
   
    return $new_content;
}
add_filter('the_content', 't4a_insert_ad_in_content');

This proved helpful in my situation.

I place an ad before and after a post automatically.
Next I try to place one in the article, before the 2nd <H2>  tag.
And finally I place one near the comments form.

This would ad up to 4 ads, which is one too many.
However,… when the ad injection fails (for very short articles), I’d optionally prefer to see one near the comments form, and that’s why the build in counter is useful. When calling the “t4a_generate_google_ad_code” function the 4th time, it will return nothing and not place an ad. If the injection failed however, this would have been the 3rd function call and an ad would appear.

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are no comments yet.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.