How to Add Block Templates to Your WordPress Theme or Plugin Gutenberg

How to Add Block Templates to Your WordPress Theme or Plugin

While working on my Gutenberg Development Course, one of the hardest things I found to research was how to add block templates to your WordPress theme or plugin.

Example of a block template with and image and paragraph block

Example of a simple template with image and paragraph block

Block templates are a way to have certain blocks show up by default for a new post, page or custom post type.  You can also “lock” the template to prevent users from adding or removing blocks.

 

How Block Templates Work

Templates are added as a parameter when registering a post type in WordPress.  Sometimes this is done for your own custom post type.  But it can also be done for existing and native post types like Posts and Pages.

The block template setting itself is an array of blocks that you want included.  There is also an additional setting called “template_lock” that can be set to true or false to lock down the template to users.

You can also add additional configurations like custom placeholder text for blocks or set the alignment.

An Example of Block Templates

You can add the code below to any plugin or theme to modify template setting for post types of your choice.

Some notes on this code:

  • Notice the conditional statement determining what post type to apply this to.  Can change for your own needs.
  • The template_lock argument determines whether users can add or remove blocks with this post type.
  • The name used for blocks is the name used when creating them.  See a list here of all default blocks, which you can use to lookup (or guess) the programatic name for a block.
  • You can add additional configurations like placeholder text, alignment, or other block attributes you want set by default.

Learn More About Gutenberg Development

To learn more about developing with blocks in WordPress, please check out my course Gutenberg Development Course.

4 thoughts on “How to Add Block Templates to Your WordPress Theme or Plugin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s