Skip to content

Commit

Permalink
Merge pull request #7 from humanmade/current-level-handling
Browse files Browse the repository at this point in the history
Better current level handling
  • Loading branch information
mattheu authored Sep 23, 2024
2 parents 270685e + 06bcafe commit f996864
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
21 changes: 19 additions & 2 deletions block/build/render.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,31 @@

namespace HM\TOC;

use WP_HTML_Tag_Processor;

$post_id = isset( $attributes['postId'] ) ? $attributes['postId'] : ( $block->context['postId'] ?? null );
$post = get_post( $post_id );

if ( ! $post ) {
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 ) ) {
Expand All @@ -23,6 +41,5 @@
);

printf( '<h2>%s</h2>', 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 '</div>';
21 changes: 19 additions & 2 deletions block/src/render.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,31 @@

namespace HM\TOC;

use WP_HTML_Tag_Processor;

$post_id = isset( $attributes['postId'] ) ? $attributes['postId'] : ( $block->context['postId'] ?? null );
$post = get_post( $post_id );

if ( ! $post ) {
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 ) ) {
Expand All @@ -23,6 +41,5 @@
);

printf( '<h2>%s</h2>', 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 '</div>';

0 comments on commit f996864

Please sign in to comment.