Site logo

Archived topic

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

3 replies · Started by Caro on November 5, 2021

Viewing posts 1–4 of 4

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?

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.

That's BRILLIANT! Thanks ever so much David! Have a great weekend :)

Awesome - glad to be of help!

This archived topic is closed to new replies.