Search code examples
wordpresswordpress-gutenberggutenberg-blockscreate-guten-block

How to exclude parent block from innerBlocks?


I want to make a Section block in WordPress Gutenberg. I have created a section block and used Gutenberg <InnerBlocks> component as inner/child blocks. It is working fine but Section block itself showing as its inner blocks list. I want to exclude the Section block from its inner blocks. <InnerBlocks> component has a property allowedBlocks to specify blocks to allow as inner blocks. But it does not help me because I only want to disallow Section blocks from inner blocks. How can I disallow only a single specific block from <InnerBlocks>?

I need an option like disallowedBlocks so that I can exclude block from innerBlocks list like

<InnerBlocks disallowedBlocks={['leo-block/section']} />

Full code

;(function(wp) {
    const {registerBlockType} = wp.blocks;
    const {InnerBlocks} = wp.editor;
    const {__} = wp.i18n;

    registerBlockType('leo-block/section', {
        title: __('Section'),
        icon: 'grid-view',
        category: 'vr-blocks',
        descrition: __('Section block for manage content section'),
        attributes: {
            content: {
                default: 'Hello World'
            },
            spacing: {
                default: {
                    paddingTop: '70px',
                    paddingBottom: '70px',
                    marginTop: '0',
                    marginBottom: '0'
                }
            }
        },

        edit: ({attributes, setAttributes, className, isSelected}) => {
            return (
                <section className = {className} style={attributes.spacing}>
                    <div className="container">
                        <InnerBlocks/> 
                        {/* TODO: Not allow "leo-block/section" */}
                    </div>
                </section>
            )
        },

        save: ({attributes, className}) => {
            return (
                <section className = {className} style={attributes.spacing}>
                    <div className="container">
                        <InnerBlocks.Content/>
                    </div>
                </section>
            )
        }
    })
})(window.wp)

Output Screenshot

Output screehshot


Solution

  • Use the following snippet, it'll give you a list of allowed blocks except your leo-block/section. And if you want then you can add more exceptions. And you know what to do with it 🙂

    const ALLOWED_BLOCKS = wp.blocks.getBlockTypes().map(block => block.name).filter(blockName => blockName !== 'leo-block/section');