Insert Ads Every 3 Times Paragraph
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');