Archived topic
How to add block/text/html before H2 tag
1 reply · Started by Evan Kristine on March 18, 2021
Viewing posts 1–2 of 2
Hi,
I'm trying to add an HTML code (box with text) that contains my CTA before the first H2 using hooks (atm I'm adding it manually). However, I can't seem to replicate this automatically sitewide using hooks. Please help. Thank you!
Hi there,
you would need to filter the_content - try this PHP Snippet:
add_filter( 'the_content', 'db_suffix_first_h2_custom_html' );
function db_suffix_first_h2_custom_html( $content ) {
$html = '<div>My custom HTML after first H2</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $html, 2, $content );
}
return $content;
}
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</h2>';
$paragraphs = explode( $closing_p, $content );
if ($paragraphs) {
$paragraphs[0] = $paragraphs[0].'</h2>'.$insertion;
}
return implode( '', $paragraphs );
}
Update the $html = '<div>My custom HTML after first H2</div>'; to include your HTML.
This archived topic is closed to new replies.