Search code examples
wordpresswordpress-gutenberggutenberg-blocks

WORDPRESS - Default blocks loaded on new post


Is is possibile, when creatin a new post, custom post type or page, to be loaded with all the blocks automatically for the layout?


Solution

  • Yes,

    If you're registering a new custom post type, use the template attribute and then create a nested array with the block's name and another nested array with any of the block's attributes that you want to fill out. If you don't know a block's attributes, you can typically find them the block's block.json file

    An example for the custom post type as follows:

    'template' => array(
                array(
                    'core/paragraph',
                    array(
                        'align'   => 'center',
                        'content' => 'Place content you already in the block, even a link to a site like <a href="stackoverflow.com">stackoverflow</a>.',
                    ),
                ),
                array(
                    'core/buttons',
                    array(
                        'layout' => array(
                            'type'           => 'flex',
                            'justifyContent' => 'center',
                        ),
                    ),
                    array(
                        array(
                            'core/button',
                            array(
                                'text'      => 'button text',
                                'url'       => 'https://the-url.com/',
                                'className' => 'a-custom-class-name',
                            ),
                        ),
                    ),
                ),
    

    For existing post types, create a callback function that you hook into init as shown in the Gutenberg documentation.