[Resolved] Insert HTML element above first h2 in single posts

Home Forums Support [Resolved] Insert HTML element above first h2 in single posts

Home Forums Support Insert HTML element above first h2 in single posts

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #873194
    Dan

    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.

    #873244
    David
    Staff
    Customer Support

    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 );
    }
    #873274
    Dan

    Thanks once again David – excellent ๐Ÿ™‚

    #873300
    David
    Staff
    Customer Support

    Glad to be of help.

    #1596093
    Austin

    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?

    #1596099
    Elvin
    Staff
    Customer Support

    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. ๐Ÿ™‚

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.