[Resolved] How to add a block hook before the first H2 heading?

Home Forums Support [Resolved] How to add a block hook before the first H2 heading?

Home Forums Support How to add a block hook before the first H2 heading?

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1992383
    Caro

    Hi team — happy Friday!

    I’m trying to add a block hook element.

    I’ve created a table of contents and would like to place it before the first H2 heading in each post. How can I do this please?

    #1992459
    David
    Staff
    Customer Support

    Hi there,

    Is it friday already lol – happy friday too.

    Simplest way is to use the Ad Inserter Plugin, they do all the messy grunt work and may be more reliable then this method using a PHP Snippet:

    add_shortcode('portable_hook', function($atts){
    	ob_start();
            $atts = shortcode_atts( array(
                'hook_name' => 'no foo'
            ), $atts, 'portable_hook' );
    		do_action($atts['hook_name']);
    	return ob_get_clean();
    });
    
    add_filter( 'the_content', 'insert_featured_image', 20 );
    function insert_featured_image( $content ) {
        global $post;
        $inserted_hook = do_shortcode('[portable_hook hook_name="custom_toc_hook"]');
        if ( is_single() && ! is_admin() ) {
            return prefix_insert_after_paragraph( $inserted_hook, 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 );
    }

    With that code added in the Hook Element choose Hook: Custom Hook and add: custom_toc_hook

    NOTE: this method is filtering the_content of the post, and it can be a little hit and miss, particularly if other plugins are also filtering it.

    #1993101
    Caro

    That’s BRILLIANT! Thanks ever so much David! Have a great weekend 🙂

    #1993306
    David
    Staff
    Customer Support

    Awesome – glad to be of help!

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