Wednesday, May 14, 2014

How to Insert Ads In Between Content In WordPress, Without Any Plugin

Here is the method:
1. In your theme folder, open the functions.php file with a text editor.
2. Insert the following lines to the end of the file, before the “?>” tag
add_filter('the_content', 'mte_add_incontent_ad');
function mte_add_incontent_ad($content)
{ if(is_single()){
  $content_block = explode('<p>',$content);
  if(!empty($content_block[2]))
  { $content_block[2] .= 'insert_ad_code_here';
  }
  for($i=1;$i<count($content_block);$i++)
  { $content_block[$i] = '<p>'.$content_block[$i];
  }
  $content = implode('',$content_block);
 }
 return $content; 
}
Remember to change the “insert_ad_code_here” string to the actual ad code. Also, if there is any instance of single quote (‘) in your ad code, you have to add a \ before it. For example, if your ad code is something like:
<div id='div-gpt-ad-1234567-1' style='width:300px; height:100px;'>
    <script type='text/javascript'>
        googletag.cmd.push(function() { googletag.display('div-gpt-ad-1234567-1'); });
    </script>
</div>
You have to make them all into one line and insert a \ before the single quote:
<div id=\'div-gpt-ad-1234567-1\' style=\'width:300px; height:100px;\'><script type=\'text/javascript\'>googletag.cmd.push(function() { googletag.display(\'div-gpt-ad-1234567-1\'); });</script></div>
What we are doing with this function is to take the content for each post and break it up into each paragraph. We then detect whether the third paragraph exists. If yes, we insert the ad code to the end of the paragraph. Lastly, we insert back the starting paragraph tag to each section and glue them back into a complete article.
Things you can change here include:
1. The paragraph to insert the ad tag. The default in the above code is the third paragraph. You can change to the second paragraph by changing all instances of $content_block[2] to $content_block[1].
Note: The count of the array starts from 0, so $content_block[2] means the third paragraph instead of the second.
2. The tag to break the article. I used the paragraph tag <p> to break the article. You can use <h2> or <h3> tag instead as the marker.
3. The ad code. You don’t necessarily have to insert ad in-between the content. You can insert newsletter subscription form or any other stuff that you deem appropriate for your site.
Lastly, don’t forget to save the file and upload it to the server. As I mentioned earlier, it is best to test this on a staging site first before making it live.

No comments: