2019-01-09_095917

Some of you have asked about adding Ads/Banner between paragraphs in a Text Chapter (or Web Novel content). It’s quite easy using “the_content” filter. It’s too small so we don’t want to create an add-on for this feature. So here you are, the code. You can place this custom code in your child theme functions.php

add_filter(‘the_content’, ‘madara_text_chapter_filter’);
function madara_text_chapter_filter($content){
$manga_id = get_the_ID();
$chapter_slug = get_query_var( ‘chapter’ );
$chapter_type = get_post_meta( $manga_id, ‘_wp_manga_chapter_type’, true );

/**
* First, we need to make sure this is the filter called from main content
**/

if($chapter_type == ‘text’){

$tag = preg_quote(‘p’);
preg_match_all(‘{<‘.$tag.'[^>]*>(.*?)</’.$tag.’>}’, $content, $matches, PREG_PATTERN_ORDER);

if(count($matches[0]) > 0){
// now $matches[0] will have all paragraph in content
// this variable holds the index of the paragraph that you want to append the Ads
$paragraph_index = 0;
$ads_content = ‘<p>YOUR AD CONTENT</p>’;

if(isset($matches[0][$paragraph_index])){
$content = str_replace($matches[0][$paragraph_index], $matches[0][$paragraph_index] . $ads_content, $content);
}
}
}

return $content;
}

In the above code, you need to change

  • $ads_content which holds the ads code, such as an image banner
  • $paragraph_index which holds the index of the paragraph in the content of which the ads will appear after that
  • You can also use $manga_id and $chapter_slug to differentiate ad content for different chapters/novels. For example

if($manga_id == 123 && $chapter_slug = ‘chapter-1’){

$ads_content = ‘DIFFERENT ADS CONTENT’;

}

Note: in the above sample, use ‘  (single quote) , not ` (a back-ward quote)

SHARE THIS POST

Leave a Reply

Your email address will not be published. Required fields are marked *

*

2 × 4 =