How to Insert Ads into Post Content in WordPress

Are you want to increase your earning by insert ads into the blog post content? If so, this tutorial will help you to add ads between the post content in WordPress without using any plugin. Most of the beginners add the ads code manually into the post content which is very time consuming and maintaining ads very difficult. Perhaps you have seen some blogs to display ads into their post content to increase blog earning. Don’t worry, here we’ll show you a simple way to insert ads or other content into your blog post in WordPress.

Not only the ads but also you can display some promotions or relative post links within the post content. Using add_filter() function in WordPress, we can easily modify the post content before rendering it. With our simple code, you can insert ads code including AdSense code and other content into the post content in WordPress without any plugin.

Open the functions.php file of your current theme and paste the following code.

/*
 * Insert ads code into post content
 * $adsCode: Specify code that wants to add
 * $insertAfter: Specify paragraph number
 */
add_filter('the_content''cw_insert_post_ads');
function 
cw_insert_post_ads($content){
    if(
is_single()){
        
//ads code
        
$adsCode '<div>Insert your ads code here</div>';
        
        
//insert after
        
$insertAfter 2;
        
        
$closingP '</p>';
        
$contentBlock explode($closingP$content);
        foreach(
$contentBlock as $key => $con){
            if(
trim($con)) {
                
$contentBlock[$key] .= $closingP;
            }
            if((
$key 1) == $insertAfter){ 
                
$contentBlock[$key] .= $adsCode;
            }
        }
        
$content implode(''$contentBlock);
    }
    return 
$content;    
}

You only need to specify the value of the following variable based on your requirement.

  • $adsCode – Insert the ads code (adsense, amazon, etc) or other content (banner, HTML, etc) which you want to insert into the post content.
  • $insertAfter – Specify the number of the paragraph. Your ads will be displayed after the specified paragraph.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

4 Comments

  1. Xaib Said...
  2. IHuongDan Blog Said...
  3. Francesca Said...
  4. Edos Ubebe Said...

Leave a reply

keyboard_double_arrow_up