admin管理员组

文章数量:1122846

I have my own custom block with an InnerBlock component which is kind of a container for the contents of each section in the document.

The whole process of adding content always starts with adding this block. Therefore, I would like to limit the selection of first level blocks to only this one block.

Once the user has added this block, then he can add other blocks inside.

This is a question without a code example as I have no idea where to start. I've seen an idea like templates, but that's not appropriate in this case.

Goal to be achieved (in simple words):

  • the user creates a new post
  • can only select one specific block
  • only in this block he can select other available blocks
  • it can happen multiple times in one post

I have my own custom block with an InnerBlock component which is kind of a container for the contents of each section in the document.

The whole process of adding content always starts with adding this block. Therefore, I would like to limit the selection of first level blocks to only this one block.

Once the user has added this block, then he can add other blocks inside.

This is a question without a code example as I have no idea where to start. I've seen an idea like templates, but that's not appropriate in this case.

Goal to be achieved (in simple words):

  • the user creates a new post
  • can only select one specific block
  • only in this block he can select other available blocks
  • it can happen multiple times in one post
Share Improve this question edited Oct 29, 2020 at 17:35 kanlukasz asked Oct 29, 2020 at 13:31 kanlukaszkanlukasz 5348 silver badges24 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Create a new custom block, lets call it CustomSecondary, that contains an InnerBlocks instance.

When registering this block set it's parent property to your main custom block and

registerBlockType(
    'custom-secondary',
    {
        parent: ['your-main-block],
        edit: () => ( <InnerBlocks />)
        { .. your other properties }
    });

This will make it so this block can only be inserted into your main block.

In the edit property of your main block add the allowedBlocks props to your InnerBlocks instance and only allow your custom-secondary block

<InnerBlocks allowedBlocks={[ 'custom-secondary' ]} />

Now when you insert, you'll only have that option and then the custom-secondary can have any blocks you want inside.

To control the template for the post it self, you can add the following filter:

function myplugin_register_template() {
    $post_type_object = get_post_type_object( 'post' );
    $post_type_object->template = array(
        array( 'core/image' ),
    );
}
add_action( 'init', 'myplugin_register_template' );

You might want to consider using locked template with a single block that can have items inserted into it.

本文标签: How to limit the selection of the first level block in Gutenberg editor