diff --git a/block/build/render.php b/block/build/render.php index e83949c..f65a2f4 100644 --- a/block/build/render.php +++ b/block/build/render.php @@ -2,6 +2,8 @@ namespace HM\TOC; +use WP_HTML_Tag_Processor; + $post_id = isset( $attributes['postId'] ) ? $attributes['postId'] : ( $block->context['postId'] ?? null ); $post = get_post( $post_id ); @@ -9,6 +11,22 @@ return; } +$max_level = $attributes['maxLevel'] ?? 3; + +// Work out the current level by finding the heighest level heading within the content. +// Typically this is H2. But technically it can be anything. +foreach ( array_slice( [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ], 0, $max_level ) as $i => $heading_tag ) { + $tags = new WP_HTML_Tag_Processor( $post->post_content ); + if ( $tags->next_tag( $heading_tag ) ) { + $current_level = $i + 1; + break; + } +} + +if ( ! $current_level ) { + return; +} + $hierarchy = get_header_hierarchy( $post ); if ( empty( $hierarchy ) ) { @@ -23,6 +41,5 @@ ); printf( '

%s

', esc_html__( 'Table of contents', 'hm-table-of-contents' ) ); -the_heading_list( $hierarchy, $attributes['maxLevel'] ?? 3 ); - +the_heading_list( $hierarchy, $max_level, $current_level ); echo ''; diff --git a/block/src/render.php b/block/src/render.php index e83949c..f65a2f4 100644 --- a/block/src/render.php +++ b/block/src/render.php @@ -2,6 +2,8 @@ namespace HM\TOC; +use WP_HTML_Tag_Processor; + $post_id = isset( $attributes['postId'] ) ? $attributes['postId'] : ( $block->context['postId'] ?? null ); $post = get_post( $post_id ); @@ -9,6 +11,22 @@ return; } +$max_level = $attributes['maxLevel'] ?? 3; + +// Work out the current level by finding the heighest level heading within the content. +// Typically this is H2. But technically it can be anything. +foreach ( array_slice( [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ], 0, $max_level ) as $i => $heading_tag ) { + $tags = new WP_HTML_Tag_Processor( $post->post_content ); + if ( $tags->next_tag( $heading_tag ) ) { + $current_level = $i + 1; + break; + } +} + +if ( ! $current_level ) { + return; +} + $hierarchy = get_header_hierarchy( $post ); if ( empty( $hierarchy ) ) { @@ -23,6 +41,5 @@ ); printf( '

%s

', esc_html__( 'Table of contents', 'hm-table-of-contents' ) ); -the_heading_list( $hierarchy, $attributes['maxLevel'] ?? 3 ); - +the_heading_list( $hierarchy, $max_level, $current_level ); echo '';