Automatically insert adsense ads between post paragraphs

Learn more here!

If you are familiar with the wordpress template files (single.php, index.php etc) you will know how to display adsense or any other ads before or after the content. But what if you automatically want to insert those ads after certain paragraph inside the post, so you won’t bother placing those ads manually when writing your posts.

It’s a bit tricky part, but luckily can be done using the php explode function.

How to insert ads after certain paragraph?

When writing a new post, be it from the visual or html tab, when you press enter, wordpress automatically opens a new paragraph and closes the already opened one. Alternatively, another function can be used to display the add after certain amount of characters, but here i will show you a way to display them after your prefered number of paragraphs.

  1. Open your single.php file from your template
  2. Look for
  3. Replace that function with the codes shown bellow

<?php
$paragraphAfter= 1; //display after the first paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
for ($i = 0; $i <count($content); $i++) {
if ($i == $paragraphAfter) { ?>

<div>
Insert your add codes here
</div>

<?php
}
echo $content[$i] . "</p>";
} ?>

This function will insert the add after the first paragraph. Change the number to whatever you think will probably work for you - i am currently displaying the ads after the 5th paragraph.
Do note: If you set the ads to be shown after the 5th paragraph, and your post is shorter than 5 paragraphs, the ads won’t be displayed.

2 Responses to “Automatically insert adsense ads between post paragraphs”
  1. Exactly what I was looking for.
    Adding adsense after the first paragraph will increase CTR!
    Thanks

  2. Thanks, it worked for me - just so you know you forgot to put anything where it says “2. Look for”

    :)

Leave a Reply