WordPress: Insert Ads in Middle of Post Content

It is a good idea to add advertisement somewhere in the content area. That way, user can have a chance to click on the ads while reading the content. Its actually quite easy to achieve that using wordpress built-in add_filter function.

function insertAds($post_content) {
  // insert after the first empty line and after the first 200 words only.
  // If you like, you can count the number of words in $post_content first, then divide by 2 to get the mid point.
  // of course if your $post_content contains all code, then you need to strip them away first
  $arr = explode('</p>',$post_content);
  $words = 0;
  foreach ($arr as $k => $v) {
    if ($k != 0 && $words > 200) {
      // insert 728x90 adsense now  
      $arr[$k-1] .= "
<div style=\"text-align:center;\">
<script type=\"text/javascript\"><!--
google_ad_client = \"ca-pub-xxx\";
/* whatever your ad is */
google_ad_slot = \"xxxxx\";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type=\"text/javascript\"
src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\">
</script>
</div>
";
       break;
    }
    $words += str_word_count($v);
  }

  // now recombine all the content again
  return implode('</p>',$arr);
}

add_filter("the_content", "insertAds");
Like it.? Share it:
Tags:

Comments are closed.