If you run a blog website, most probably you will be inserting ads in your blog to generate some income. In WordPress (self-hosted), you can easily add ads to the sidebar by inserting the ad code to a text widget in the Widget section. The difficult part is to add ads to the content, particularly in-between the content. While there are some plugins that allow you to add shortcode to the content, they are not feasible if your blog already have thousands of article, unless you are willing to go back to insert the shortcode in every single article. In this article, we will show you a simple way where you can easily insert ad (or any other stuff) in-between your content without using any plugin.
Note: This method requires some meddling with the code. If you are not comfortable dealing with the code, don’t attempt it. You might also want to create a staging site of your blog and test this method on the staging site first before making it live.
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 “
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:
You have to make them all into one line and insert a \ before the single quote:
Explanation of the function
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
Note: The count of the array starts from 0, so
$content_block 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
<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.
Our latest tutorials delivered straight to your inbox