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. Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thanks for this, what if we want to show ads before and after the content also want to show in middle of content, how we can do that.
Thanks again.
I want to insert ads in the middle of the article should do
Thanks you, it’s work for me .
Thanks for putting together this incredibly awesome post, very valuable. You know most people think that they have to manually add their ads code within post content but thanks for this tutorial. It’s an eye opener.