Search code examples
javascriptwordpresswordpress-gutenberg

Register same custom styles to multiple block types in gutenberg


I want to add some styles to more than one block type.

At the moment I'm doing this for every block type like this and change only the part 'core/paragraph' to 'core/heading' for example.

Is there any way to do this for more than one block at the same time?

wp.blocks.registerBlockStyle(
'core/paragraph',
[
    {
        name: 'default',
        label: 'Default',
        isDefault: true,
    },
    {
        name: 'lead',
        label: 'Lead',
    },
    {
        name: 'subline',
        label: 'Subline',
    },
]
);

Solution

  • If you know names of the blocks you want to add your styles to, you can use registerBlockStyle() in a forEach() loop to mass register multiple styles to multiple blocks, eg:

    const blocks = ["core/quote", "core/heading", "core/paragraph"]; //etc..
    
    const styles = [
        {
            name: 'default',
            label: 'Default',
            isDefault: true,
        },
        {
            name: 'lead',
            label: 'Lead',
        },
        {
            name: 'subline',
            label: 'Subline',
        }
    ];
    
    // Loop through each block and register all custom styles in one go..
    blocks.forEach(function(blocks) {
        wp.blocks.registerBlockStyle(blocks, [...styles]);
    });
    

    To find the names of all currently registered blocks, use:

    wp.blocks.getBlockTypes().map(block => block.name);
    

    Even though you could apply your styles to every block, please use it sparingly only on required blocks - not every block all at once..