Subscribe via

How to Add Ads Inside Your Post Content

Thaya Kareeson

As a webmaster, it is always good to experiment with advertisement placements to maximize your ad revenue. One possible ad placement is in the middle of your posts. One way to do this is to manually include the ad into every one of your post text (I’m not a big fan of this idea). The better way to do it is to modify your theme to automatically show this ad in your posts’ content. Since it’s a bit tricky, I’d like to share a quick tip on how to do this.

Copy/Paste

Copy and paste the following code into your theme’s functions.php:

function inject_ad_text_after_n_chars($content) {
  // only do this if post is longer than 1000 characters
  $enable_length = 1000;
  // insert after the first </p> after 500 characters
  $after_character = 500;
  if (is_single() && strlen($content) > $enable_length) {
    $before_content = substr($content, 0, $after_character);
    $after_content = substr($content, $after_character);
    $after_content = explode('</p>', $after_content);
    $text = '
      <!-- PUT YOUR AD HERE -->
    ';
    array_splice($after_content, 1, 0, $text);
    $after_content = implode('</p>', $after_content);
    return $before_content . $after_content;
  }
  else {
    return $content;
  }
}
add_filter('the_content', 'inject_ad_text_after_n_chars');

Modify

  • Make sure to replace “PUT YOUR AD HERE” with your advertisement code.
  • $enable_length: Your ad will only be inserted if the post length exceeds this value.
  • $after_character: Your ad will be inserted after the first </p> after this value.

That’s it! Enjoy!

Save and Share
StumbleUpon
Reddit

Currently experiencing problems with Intense Debate commenting system. Please make sure your browser's Javascript is enabled and try again later.