Home > Mobile >  Insert Ads After Every X Paragraphs PHP
Insert Ads After Every X Paragraphs PHP

Time:05-31

I am currently using this code to insert Ads after the 5th paragraph and it works just fine.

//Insert ads after fifth paragraph
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
    $ad_code = '<center>AD CODE</center>';
    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 5, $content );
    }
    return $content;
}

// Parent Function
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }
        if ( $paragraph_id == $index   1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }
    return implode( '', $paragraphs );
}

But, I would like the ads to be repeated after every 5 paragraphs, not just once. What do I do?

CodePudding user response:

Instead of

if ( $paragraph_id == $index   1 ) {

you can use

if ( $index % $paragraph_id === 0 ) {

that should do it.

  • Related