Site logo

Archived topic

Insert a banner

8 replies · Started by Jörg on May 5, 2021

Viewing posts 1–9 of 9

Hi,
Im looking for an opportunity to insert a banner in every post e.g. before the second H2 headline. Is this possible, maybe with a hook?
Thanks

Hi there,

you would have to use WP's the_content filter hook to do that. Heres a PHP that will add the contents of the $html variable before the second H2.

add_filter( 'the_content', 'db_prefix_second_h2_custom_html' );

function db_prefix_second_h2_custom_html( $content ) {

    $html = '<div>My custom HTML before second H2</div>';

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

    return $content;
}
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '<h2>';
    $paragraphs = explode( $closing_p, $content );
    if ($paragraphs) {
        $paragraphs[1] = $paragraphs[1].$insertion;
    }    
    return implode( '<h2>', $paragraphs );
}

Adding PHP:
https://docs.generatepress.com/article/adding-php/

Thanks for the help,
unfortunately the banner is displayed after the content and right before the autors box. I copied the code in my child theme functions.php.
Can you help me?
Thanks

Can you share a link to your site so i can see whats going on?

The issue is because the H2 elements have an ID or an Inline style eg.

<h2 id="h-timing-ist-alles">** some content here **</h2>

That code specifically works with a simple <h2> any other code within it will not work.
And unfortunately I do not have the regex skills required to deal with variable H2 elements.

You may want to try using the Ad Inserter plugin:

https://en-gb.wordpress.org/plugins/ad-inserter/

It doesn't just do Ads - it will allow you to filter the content and any type of code you want.

Thanks for the hint. I will try that plugin.

You're welcome

This archived topic is closed to new replies.