Skip to content

Instantly share code, notes, and snippets.

@billerickson
Created May 30, 2019 21:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save billerickson/c451a7b2ef0c8ee4e48b7c17f536f39b to your computer and use it in GitHub Desktop.
Save billerickson/c451a7b2ef0c8ee4e48b7c17f536f39b to your computer and use it in GitHub Desktop.
<?php
/**
* List post headings
* @see https://www.billerickson.net/access-gutenberg-block-data/
*/
function be_list_post_headings() {
global $post;
$blocks = parse_blocks( $post->post_content );
$headings = array();
foreach( $blocks as $block ) {
if( 'core/heading' === $block['blockName'] ) {
if( false !== strpos( $block['innerHTML'], 'id=' ) ) {
$element = 'h' . $block['attrs']['level'];
$title = str_replace( array( '<' . $element, 'id="', '</' . $element ), array( '<a', 'href="#', '</a' ), $block['innerHTML'] );
} else {
$title = wp_strip_all_tags( $block['innerHTML'] );
}
$headings[] = $title;
}
}
if( !empty( $headings ) ) {
echo '<ol class="table-of-contents">';
foreach( $headings as $heading )
echo '<li>' . $heading . '</li>';
echo '</ol>';
}
}
add_action( 'genesis_before_entry', 'be_list_post_headings' );
@certainlyakey
Copy link

Unfortunately there's a bug in Gutenberg now that only fills $block['attrs']['level'] for H1 headings.

@billerickson
Copy link
Author

Hopefully the bug will be resolved soon. There's no good reason for WordPress to not include the heading level in there.

@LukaszJaro
Copy link

Same issue with https://github.com/sortabrilliant/guidepost

No column support due to gutenberg bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment