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_first($matches[0][$paragraph_index], $matches[0][$paragraph_index] . $ads_content, $content);
}
}
}

return $content;
}

function str_replace_first($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);
}

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)

(Full source code: https://app.box.com/s/z638nen7w7ncfi2wlhe7zx33ecymo59c)

SHARE THIS POST

1 Comment

  1. Darkcry

    This not work ? give a error

    Your PHP code changes were rolled back due to an error on line 38 of file wp-content/themes/madara-child/functions.php. Please fix and try saving again.

    syntax error, unexpected ‘{‘, expecting ‘)’

    and this is the line 38
    preg_match_all(‘{]*>(.*?)}’, $content, $matches, PREG_PATTERN_ORDER);

Leave a Reply

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

*

twelve − 1 =