Heading Outline Panel With Skipped-Level Warnings
Adds a "Heading outline" panel to the block editor sidebar that lists the post's headings as an indented outline and flags skipped levels (such as an H2 followed by an H4) and empty headings.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-heading-outline', '', array( 'wp-plugins', 'wp-editor', 'wp-element', 'wp-data' ), null, true );
wp_enqueue_script( 'wpide-heading-outline' );
wp_add_inline_script( 'wpide-heading-outline', <<<'JS'
(function (wp) {
var el = wp.element.createElement;
var Panel = (wp.editor && wp.editor.PluginDocumentSettingPanel) || (wp.editPost && wp.editPost.PluginDocumentSettingPanel);
if (!Panel) { return; }
function headings(blocks, out) {
blocks.forEach(function (b) {
if (b.name === 'core/heading') { out.push(b); }
if (b.innerBlocks && b.innerBlocks.length) { headings(b.innerBlocks, out); }
});
return out;
}
function Outline() {
var list = wp.data.useSelect(function (select) { return headings(select('core/block-editor').getBlocks(), []); }, []);
var prev = 1;
var items = list.map(function (b) {
var level = b.attributes.level || 2;
var text = String(b.attributes.content || '').replace(/<[^>]+>/g, '').trim();
var problems = [];
if (level > prev + 1) { problems.push('skips from H' + prev + ' to H' + level); }
if (level === 1) { problems.push('extra H1'); }
if (!text) { problems.push('empty'); }
prev = level;
return el('li', { key: b.clientId, style: { marginLeft: (level - 2) * 12 + 'px', color: problems.length ? '#b32d2e' : 'inherit' } },
'H' + level + ' ' + (text || '(empty)') + (problems.length ? ' - ' + problems.join(', ') : ''));
});
return el(Panel, { name: 'wpide-heading-outline', title: 'Heading outline' },
list.length ? el('ul', { style: { margin: 0 } }, items) : el('p', null, 'No headings yet.'));
}
wp.plugins.registerPlugin('wpide-heading-outline', { render: Outline });
})(window.wp);
JS
);
} );
Notes
The post title is the page's H1, so the outline expects content headings to start at H2.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.