Archived topic
Insert HTML element above first h2 in single posts
5 replies · Started by Dan on April 18, 2019
Hey Guys
Don't believe this is covered elsewhere on the forum but if so I apologise.
I am trying to insert an HTML asset above the first h2 in relevant posts. So far I have created the asset in Elements and it working correctly on page when assigned against one of the standard locations.
What I need to do now is work out how to position it above the first h2, which I assume requires a combination of custom hook and a snippet to insert reference to that hook in the functions.php?
Any advice appreciated.
Hi there,
you would need to use a filter hook - for example this snippet will add custom HTML element before the first H2 on all single posts:
add_filter( 'the_content', 'db_prefix_first_h2_custom_html' );
function db_prefix_first_h2_custom_html( $content ) {
$html = '<div>My custom HTML before first 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[0] = $paragraphs[0].$insertion;
}
return implode( '<h2>', $paragraphs );
}
Thanks once again David - excellent :-)
Glad to be of help.
I'm attempting to do the same thing, but this hook isn't working for me. I copy and pasted it into a custom hook element, added in the correct HTML (checked and double checked to make sure it was right), and tried assigning it to WP head targeting all single posts, with no luck. It just messed up my formatting.
Any idea what I might be doing wrong?
Hi Austin,
As this particular topic is pretty old, can you open up a new topic for your site?
So you can use the private information text field to provide the site details. Thank you. :)