DEV Community

Cover image for How to Create WordPress Gutenberg Block Templates
alvinarichard
alvinarichard

Posted on

How to Create WordPress Gutenberg Block Templates

There are two ways of creating customized Gutenberg block templates.

1. Registering Gutenberg Blocks

In the first step we create custom blocks templates that can be used to build pre-populated blocks. Add the following code to the functions.php.

add_action( 'init', function() {
$args = array(
'public' => true,
'label' => 'News',
'show_in_rest' => true,
'template_lock' => 'all',
'template' => array(
array( 'core/paragraph', array(
'placeholder' => 'Breaking News',
) ),
array( 'core/image', array(
'align' => 'right',
) ),
),
);
register_post_type( 'news', $args );
} );

In the above code the array parameter ‘core/paragraph’ is responsible for the content of the block and array parameter ‘core/image’ allows you to upload images

For adding custom block to this template, use the ‘template’ sub-array.


'template' => array(
array( 'core/heading', array( 'level' => '4', 'content' => 'Heading' ) ),
array( 'core/paragraph' ),
)

2. Creating a Gutenberg Plugin
While working with custom templates, the best way is to create a Gutenberg editor plugin.

To create the plugin, go to the wp-content/plugins directory and create a new folder. The name of the folder must be the name of the custom Gutenberg template plugin. Here I have named my plugin as Gutenberg Blocks.

Create a file named Gutenberg-blocks.php and add the following code


add_action( 'init', function() {
$args = array(
'public' => true,
'label' => 'News',
'show_in_rest' => true,
'template_lock' => 'all',
'template' => array(
array( 'core/paragraph', array(
'placeholder' => 'Breaking News',
) ),
array( 'core/image', array(
'align' => 'right',
) ),
),
);
register_post_type( 'news', $args );
} );

Top comments (0)