Required (mandatory) Gutenberg block

Is there any way to force a Gutenberg block to be on every page of a post type?

I tried to add a template on my page and it does almost what I need, but I can still remove my default blocks.

The closest I’ve come is this:

function ckt_mina_init_required_block()
{
    // create a new page template (pages only)
    $page_type_object = get_post_type_object('page');
    $page_type_object->template = [
        [
            'core/group',
            [],
            [
                // add a paragraph block for the page summary
                [
                    'core/paragraph',
                    [
                        'placeholder' => __('Excerpt'),
                    ],
                ],
                [
                    'core/image',
                    [],
                ],
            ],
        ],
    ];
    $page_type_object->template_lock = 'all';
}

add_action('init', 'ckt_mina_init_required_block');

This will create a new page template and use it on every new page. The 2 blocks “paragraph” and “image” will be present in the first group.

But I cannot add any other block to my page.

Or, I can remove the template_lock = 'all', but then, my blocks can be removed during the page creation.

Any idea on how I might achieve to have 2 fixed blocks at the beginning of my Gutenberg area?

1 Answer
1

No fast and easy solution for you. Read discussion here and here.

You may try to write some rather sophisticated Gutenberg code to implement this feature, or maybe you could implement some save_post hook to check saved block structure with parse_blocks and do something if they don’t match your required structure. For example, prevent post publication or insert required blocks into content.

Leave a Comment