How to Insert Ads After Every X Paragraph PHP

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 = 'centerAD 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?

Topic php Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.