Inserting content (like ad code) after a random number of paragraphs

Display your ad code (or any content) inserted after a varying number of paragraphs so that your ads shift around the page from one page load to the next. rather than always being displayed in the same position.

Inserting ads midway through the_content is a great WordPress upgrade for monetized sites -such as displaying an ad after the 2nd paragraph in each post/page. But by simply making the paragraph number random, your ad code moves around the page, keeping the viewing experience unique for each page load.

advanced: You can upgrade yet further by having this shifting ad block display rotating content (ad code or other) randomly selected from a widget. Read more »

Use the following code to replace your current

<?php the_content();?>

such as in your WordPress theme’s single.php and page.php

$after_p = rand(2,14);
$content = apply_filters('the_content', $post->post_content);
if(substr_count($content, '<p>') > $after_p)
$contents = explode("</p>", $content);
$p_count = 1;
foreach($contents as $content)
echo $content;

if($p_count == $after_p)
<div class="ad">
<!– Your Ad Code Here –>
echo "</p>";

In the new code, you’ll want to

  1. replace <!– Your Ad Code Here –> with your ad code or other content
  2. and also set the range of paragraphs where it says rand(2,14) this is saying choose a random paragraph between the 2nd and 14th of the article. If your site has longer articles, set it higher. If an article is shorter than the number of paragraphs in this setting, the inserted content will sit at the end of the last paragraph.

Want to show random ads in that shifting ad block? It’s just a few more simple steps. Read on »

Leave a Reply