Monday, February 7, 2022

[FIXED] How to insert ads code before every H2 tags?

Issue

I want to show ads before every h2 tag on my blog. I got an answer here which is only for the first h2 tag. The code is below.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = 'ADS_CODE';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 1, $content );
    }

    return $content;
}

//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '<h2>';
    $paragraphs = explode( $closing_p, $content );
    if ($paragraphs) {
        $paragraphs[0] = $paragraphs[0].$insertion;
    }    
    return implode( '<h2>', $paragraphs );
}

Solution

With a small change in your code, all headings will be processed

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = 'ADS_CODE';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 1, $content );
    }

    return $content;
}

//Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '<h2>';
    $paragraphs = explode( $closing_p, $content );
    $adv_insert = array_map(fn ($a) => $a . $insertion, $paragraphs);    
    return implode( '<h2>', $adv_insert );
}


Answered By - EM4D

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.