Gutenberg keyboard shortcut for headings

I use Gutenberg a lot for editing WordPress post and page content. In order to improve readability and SEO results, I add headings to some sections of the content using the WordPress core “heading” block. However, adding them and changing the heading level (H2, H3, H4, H5 or H6) is a bit of a pain, because it involves moving away from the keyboard to use the mouse and set the heading levels.

This is easy to improve for a WordPress developer: add block variations, which allow the use of the keyboard “/” shortcut to add them directly. Block variations are simply customised versions of existing blocks, with alternative attributes set. This means that you can provide the block variation “h3”, which the user can insert by typing /h3 and then hitting enter.

Add this example to the script you load in the Gutenberg editor, and you have your six block variations.

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h1',
    title: 'H1',
    attributes: { level: 1 }
});

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h2',
    title: 'H2',
    attributes: { level: 2 }
});

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h3',
    title: 'H3',
    attributes: { level: 3 }
});

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h4',
    title: 'H4',
    attributes: { level: 4 }
});

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h5',
    title: 'H5',
    attributes: { level: 5 }
});

wp.blocks.registerBlockVariation('core/heading', {
    name: 'sht/h6',
    title: 'H6',
    attributes: { level: 6 }
});

(The sht prefix is a unique namespace, intended to avoid conflict with other scripts which add block variations. Use your own prefix instead of sht.)

Leave a Reply

Your email address will not be published. Required fields are marked *