Home / Widgets / TOC before first heading
Duplicate Snippet

Embed Snippet on Your Site

TOC before first heading

Output the TOC block before the first heading in a post

Code Preview
php
<?php
/**
 * TOC After First Heading
 */
function cwp_toc_after_first_heading( $output, $block ) {
	if ( 'core/heading' !== $block['blockName'] ) {
		return $output;
	}
	global $wp_query;
	if ( ! $wp_query->in_the_loop ) {
		return $output;
	}
	// Only run once.
	remove_filter( 'render_block', 'cwp_toc_after_first_heading', 10, 2 );
	$toc = render_block( [ 'blockName' => 'cwp/toc', 'attrs' => [ 'name' => 'cwp/toc', 'mode' => 'preview' ] ] );
	return $toc . $output;
}
add_filter( 'render_block', 'cwp_toc_after_first_heading', 10, 2 );

Comments

Add a Comment