Skip to content

Commit

Permalink
Update render.php
Browse files Browse the repository at this point in the history
  • Loading branch information
mattheu authored Sep 23, 2024
1 parent 44539b7 commit 06bcafe
Showing 1 changed file with 19 additions and 2 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>';

0 comments on commit 06bcafe

Please sign in to comment.