Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.