How can I change registered blocks “parent” based on message type?

How can I change registered blocks “parent” based on message type?

I want to achieve the following:

When creating a new page, a “core/group” block must be inserted by default. Users should only be able to add content within this block, while it should not be possible to add further blocks at the root level.

I achieved this behavior with the following code:

// Add template to "page" post type object, lock template
function my_register_default_page_template() {
    $pt = get_post_type_object( 'page' );

    if ( ! $pt ) {
        return;
    }

    $pt->template = array(
        array(
            'core/group',
            array(
                'metadata' => array(
                    'name' => 'My Root Group',
                ),
                'layout' => array(
                    'type' => 'constrained',
                ),
                'lock' => array(
                    'move'   => true,
                    'remove' => true,
                ),
            ),
            array(
                array( 'core/paragraph' )
            ),
        ),
    );
}
add_action( 'init', 'my_register_default_page_template' );

The child paragraph is added only to force the block editor not to offer the “choose group type” UI.

// Hide default "Add Block" button
function my_enqueue_block_editor_assets() {
    $screen = get_current_screen();

    if ( ! $screen || $screen->post_type !== 'page' ) {
        return;
    }

    wp_add_inline_style(
        'wp-edit-blocks',
        '.block-editor-button-block-appender { display:none !important; }'
    );
}
add_action( 'enqueue_block_editor_assets', 'my_enqueue_block_editor_assets' );
// Restrict blocks to have core/block as parent
function my_force_group_parent( array $args, string $name ): array {
    if ( strpos( $name, 'core/' ) === 0 && $name !== 'core/group' || $name === 'my-block-lib/my-block' ) {
        // Overwrite any existing parent(s) with the "group" block.
        $args['parent'] = [ 'core/group' ];
    }

    return $args;
}
add_filter( 'register_block_type_args', 'my_force_group_parent', 10, 2 );

The last feature prevents users from dragging blocks outside the root core/group.

However, the latter function does not limit the behavior to only applying to pages, which is not possible with the register_block_type_args hook, which runs before the message is loaded and so there is no way to determine which message type we are currently editing.

What approach could I take to get this right? Any help is warmly appreciated.

#change #registered #blocks #parent #based #message #type

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *