Displaying random content/ads in a random position within the_content

This is a follow-up variation to Inserting content (like ad code) after a random number of paragraphs.

In this example, rather than display one block of content that shifts in position (randomly appearing after a paragraph between 2 and 14), we have a widget area that does so. In a minute we’re going to use this new widget area to store and serve random blocks of content (such as ad code or whatever you want).

Open up the single.php and/or page.php file(s) of your theme and replace

<?php the_content();?>

with

<?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">
<?php if ( !function_exists('dynamic_sidebar')|| !dynamic_sidebar('ads') ) : endif;} ?>
</div>
<?
}
echo "</p>";
$p_count++;
}
}
?>

Just as in our basic example, be sure 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.

    But now we also have a third, important step

  3. Register the new widget area ‘ads’

    Open up your theme’s functions.php and add the lines

    register_sidebar(array(
    'name'=>'ads',
    'before_widget' => '<div id="%1$s" class="ad %2$s">',
    'after_widget' => '</div>',
    'before_title' => '<h3 style=display:none;>',
    'after_title' => '</h3>'));

    Now you have a Widget area under Appearance > Widgets called ‘ads’

  4. Install the plugin Ad Rotator by going to Plugins > Add New in your wp-admin panel and entering Ad Rotator
  5. Reload your main Appearance > Widgets page to see the new Ad Rotator widget.
  6. Drag the Ad Rotator widget to your ‘ads’ widget area and paste your code or other content inside.
  7. To separate multiple content blocks, insert
    <!–more–> on its own line, such as:

    Ad Code 1
    <!–more–>
    Ad Code 2
    <!–more–>
    Newsletter Signup Form
    <!–more–>
    most popular articles

Leave a Reply