Add an advert every nth Paragraph

The easiest way I can think of is to go through the paragraphs adding the ad text along with your paragraphs:

function insert_ad_block( $text ) {

    if ( is_single() ) :

        $ads_text="<div class="center">" . get_field('blog_post_ad', 'option') . '</div>';
        $split_by = "\n";
        $insert_after = 3; //number of paragraphs

        // make array of paragraphs
        $paragraphs = explode( $split_by, $text);

            if ( count( $paragraphs ) > $insert_after ) {

                        $new_text="";     // new text
                        $i = 1;             // current ad index

                        // loop through array and build string for output
                        foreach( $paragraphs as $paragraph ) {
                            // add paragraph, preceeded by an ad after every $insert_after
                            $new_text .= ( $i % $insert_after == 0 ? $ads_text : '' ) . $paragraph;
                            // increase index
                            $i++;
                        }

                        return $new_text;
            }


            // otherwise just add the ad to the end of the text
            return $text . $ads_text;

    endif;

    return $text;

}
add_filter('the_content', 'insert_ad_block');

This script keeps track of which paragraph it is looking at with $i and appends the ad after every $insert_after. The index starts counting at 1 (not 0) to avoid opening the post with an ad. This script could use a bit of finessing.

As a sidenote, using line breaks can be a bit tricky in determining paragraphs, as it can introduce ads in the middle of lists, or put multiple ads on top of each other when the user is trying to space out items. For legibility, maybe its worth looking for </p> and running the filter very late (after wpautop). Its really a matter of balacing your business objectives with UX.

Hope that’s what you are looking for 🙂

Leave a Comment