WordPress

How to Create Gutenberg Block Templates in WordPress

Gutenberg block templates

WordPress Gutenberg editor supports customize block templates that help WordPress user to add custom block to their CMS.

Register Gutenberg Blocks

This method involves custom block templates that is used to build pre-populated blocks. Add the following code to functions.php file

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 );
} );

This is how the custom template for Gutenberg block appear.

WordPress Gutenberg Block Templates

In this code the array parameter ‘core/paragraph’ is used for the content of the block and the ‘core/image’ allows you to upload images in three ways:

  1. Direct upload
  2. Uploading from Media Library
  3. Embedding using a URL.

The ‘template_lock’ argument, when set to ‘all’, then it locks the custom blocks from being added to the template.

When it comes to adding custom block to this template, use the ‘template’ sub-array. For instance, consider the following snippet:

If you want to add a custom block to this template then use the ‘template’ sub-array. Add the following code snippet:

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

Related posts

Conversion Rate Optimization Tips to Improve Conversions and Increase Revenue

WPiTech

Enable Gutenberg Editor in Custom Post Types

WPiTech

7 Best Managed WordPress Hosting Providers [2019]

WPiTech