admin管理员组

文章数量:1133689

Background

I've created a custom top level "page section" block, to work with my existing theme. I've like to restrict top level blocks to ONLY that one block. However, I don't want to disable all blocks completely, because I want all blocks available to use as innerBlocks.

Question

How can I restrict top level blocks, without restricting child level blocks?

Background

I've created a custom top level "page section" block, to work with my existing theme. I've like to restrict top level blocks to ONLY that one block. However, I don't want to disable all blocks completely, because I want all blocks available to use as innerBlocks.

Question

How can I restrict top level blocks, without restricting child level blocks?

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Nov 27, 2019 at 17:14 KeldericKelderic 2511 silver badge12 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

The short answer is you can’t. But you can accomplish this by using a block template that only contains your block and is locked. If your block has an InnerBlocks instance, you can add any of the registered blocks to it.

add_action( 'init', 'insert_template' );
function insert_template() {
    $post_type_object = get_post_type_object( 'post' );
    $post_type_object->template =[ [ 'your-custom-block-name'] ];
    $post_type_object->template_lock = 'all';
}

You can add a custom script to the admin panel using the admin_enqueue_scripts action.

Here is an example of how you can restrict existing blocks to only be included inside certain blocks:

const restrictEditorParentBlocks = (settings, name) => {
    const TEXT_EDITOR_BLOCKS = [
        'core/heading',
        'core/image',
        'core/list',
        'core/paragraph',
        'core/shortcode',
        'core/embed',
    ];

    if (TEXT_EDITOR_BLOCKS.includes(name)) {
        settings.parent = ['example/my-custom-block-that-needs-text-editor-blocks']
    }

    console.log(settings, name)

    return settings
}

wp.hooks.addFilter(
    'blocks.registerBlockType',
    'your-project-name/restrict-parent-blocks',
    restrictEditorParentBlocks
);

This will disable them for the page, but allow them inside the specified parent blocks.

(see settings.parent assignment)

本文标签: Gutenberg Restrict Top Level BlocksBut Not Child Blocks