Insert adverts before the first h2 tag of the post content

Viewed 850

I am trying to insert an advert before the first h2 tag in a post. The code I have tried is below, but the advert comes after the content and not before. I'm looking to insert the advert before the content, and not after.

/*Insert ads after second paragraph of single post content.*/
add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = 'This is my ads';

    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 );
    foreach ($paragraphs as $index => $paragraph) {

        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }

        if ( $paragraph_id == $index + 1 ) {
            $paragraphs[$index] .= $insertion;
        }
    }

    return implode( '', $paragraphs );
}

Any help would be appreciated.

1 Answers

Try this:

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 );
}
Related