Archived topic
Insert a banner
8 replies · Started by Jörg on May 5, 2021
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?
Sure. https://tri-it-fit.de/protein-im-ausdauersport-brauchst-du-das-wirklich/
The second newsletter banner should be on top of H2.
Thanks for your help
Hi,
I just discovered that it works in other articles. Here's an example: https://tri-it-fit.de/saisonplanung-fuer-triathleten-so-planst-du-dein-jahr/
Edit: I changed the article from the old editor in Gutenberg blocks and now the banner is also at the bottom.
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