Site logo

[Support request] How to add block/text/html before H2 tag

Home Forums Support [Support request] How to add block/text/html before H2 tag

Home Forums Support How to add block/text/html before H2 tag

  • This topic has 1 reply, 2 voices, and was last updated 5 years ago by David.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1700111
    Evan Kristine

    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!

    #1700520
    David
    Staff
    Customer Support

    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.

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