-
Hi,
I was trying to create a hook element to automatically insert the RankMath TOC on all my posts.
I had a setup with a different TOC plugin and worked perfectly.But I tried to use RankMath TOC instead and it did not work.
The GeneratePress team suggested to get in touch with you to confirm if this could be possible.
Code:
/*Add Table of contents before first H2*/
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();
});function insert_hook_before_first_h2( $content ) {
global $post;
$inserted_hook = do_shortcode(‘[portable_hook hook_name=”custom_toc_hook”]’);if ( is_single() && ! is_admin() ) {
$pattern = ‘/<h2[^>]*>.*?<\/h2>\s*<p[^>]*>.*?<\/p>\s*<p[^>]*>.*?<\/p>/s’;
$content = preg_replace_callback($pattern, function($match) use ($inserted_hook) {
return $inserted_hook . $match[0];
}, $content, 1); // Add hook before the first h2
}
return $content;
}
add_filter( ‘the_content’, ‘insert_hook_before_first_h2’, 20 );Thanks for your comments,
Denise
The ticket ‘TOC hooking via shortcode’ is closed to new replies.