How to Create Block Templates in Gutenberg

The idea of page building blocks in WordPress is pretty neat, but it’s easy to see how your clients or customers could easily abuse and misuse them.

You’ve seen it happen before. A social block in the header, a comments block in the post body, twelve alerts on one page. Suddenly, the page you meticulously designed ends up looking like some kind of losing entry in a chili contest.

In this article, we’ll show you how to create your own block templates that will lay your blocks out in a pre-populated format so your clients can simply fill-in-the-blanks like an old-school MadLib. Let’s get started.

Step 1: Register a Custom Post Type

If you’ve been in the WordPress world for a while, I’m sure you’re pretty familiar with this step. However, there’s a new argument called template that you can use during CPT registration which defines the default blocks and attributes that should be populating the edit screen when a user attempts to create a new entry for that CPT. Here’s an example:

add_action( 'init', function() {
  $args = array(
    'public' => true,
    'label'  => 'Meetups',
    'show_in_rest' => true,
    'template_lock' => 'all',
    'template' => array(
      array( 'core/image', array(
        'align' => 'left',
      ) ),
      array( 'core/heading', array(
        'placeholder' => 'Add Event Title...',
      ) ),
      array( 'core/paragraph', array(
        'placeholder' => 'Add Description...',
      ) ),
    ),
  );

  register_post_type( 'meetup', $args );
} );

A few notes about some of the arguments that we’re passing during the custom post type registration:

show_in_rest tells WordPress that data about this custom post type should be able to be fetched via the WordPress REST API. As of Gutenberg 2.8, this is a requirement since Gutenberg fetches all of its data via the API.

The real magic happens within the template argument. Here, we pass an array of arrays that defines the blocks that should appear within the template. The sub-arrays that are defined are in the following format:

array(
  'blockName/blockType',
  array(
    'attributeOne' => 'Value One',
    'attributeTwo' => 'Value Two'
  )
);

Finally, you probably also noticed the template_lock property; when that is set to all, it prevents blocks from being added or removed to the template. This makes it really simply to control the end appearance of how the page is displayed.

Leave a Reply

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