Insert ads within post contents in wordpress

October 16, 2012 // In: Blogging & SEO

You have seen many blogs that have ads within post contents in wordpress. Ad appears after two, three paragraphs. Some beginner blogger thinks that its very difficult and even some beginner think that they insert adsense code manually while writing contents. Ofcourse you can insert code manually, but its not good approach because if you switch to any other advertiser than you have to replace the code manually from every post. If you have 200 posts you have to update it from 200 posts.

put ads within post contents in wordpress

Another method is to set up short code for ads, so can use that short code anywhere in the post and in that case you will not face any difficulty while switching advertiser. Read my artcle Insert ads within post contents using ShortCode

Now, Lets start,

Go to Appearance – > Editor and open single.php file and look for the line something like

<?php the_content(); ?>

Replace that line of code with

<?php
$paragraph= 4; //displays the ad after 4th paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
for ($i = 0; $i <count($content); $i++ ) {
if ($i == $paragraph) { ?>
<div>Insert Your Code Here</div>
<?php
}
echo $content[$i] . "</p>";
}
?>

You can change ads placement by changing number of paragraph in first line of the code (changing the value of $paragraph).

Insert ads within post contents using shortcode