Warn About H1 Headings in the Block Editor
Shows a warning in the block editor when a post contains an H1 heading block, since the post title is already the page's H1 and a second one muddles the outline.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-h1-warning', false, array( 'wp-data', 'wp-notices', 'wp-block-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-h1-warning' );
wp_add_inline_script( 'wpide-h1-warning', <<<'JS'
( function ( wp ) {
var id = 'wpide-h1-warning', last = null, timer = null;
var hasH1 = function ( blocks ) {
return blocks.some( function ( block ) {
return ( block.name === 'core/heading' && block.attributes.level === 1 ) || ( block.innerBlocks && hasH1( block.innerBlocks ) );
} );
};
wp.data.subscribe( function () {
clearTimeout( timer );
timer = setTimeout( function () {
var editor = wp.data.select( 'core/block-editor' );
var found = editor ? hasH1( editor.getBlocks() ) : false;
if ( found === last ) {
return;
}
last = found;
if ( found ) {
wp.data.dispatch( 'core/notices' ).createWarningNotice( 'This post contains an H1 heading. The title is already the H1, so use H2 for main sections.', { id: id, isDismissible: true } );
} else {
wp.data.dispatch( 'core/notices' ).removeNotice( id );
}
}, 400 );
} );
} )( window.wp );
JS
);
} );
Notes
The warning disappears as soon as the heading is changed to H2 or removed.
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.