Using Block Templates with Gutenberg

Block templates are one of my favorite new features in Gutenberg. You can specify a list of blocks that automatically appear in the content editor, and you can customize what appears in each block by default.

You can also lock the template so no additional blocks can be added. This is a great replacement for metaboxes in many cases. You can control the content structure without sacrificing the visual editing experience. 

Block templates are currently set for an entire post type, but you will soon have more granular control to define them in page templates and other contexts.

Quick tip on implementation

I first build the page in the Gutenberg block editor. Then I add the code below to the theme, which prints out an escaped version of post_content. This shows me the blocks and parameters I need to build the block template.

I’m using ea_pp() below (code here) but you could also use print_r().

/**
 * Display Post Blocks 
 *
 */
function ea_display_post_blocks() {
	global $post;
	ea_pp( esc_html( $post->post_content ) );
}
add_action( 'wp_footer', 'ea_display_post_blocks' );

That helped me build the following block template:

'template' => array(
	array( 'core/heading', array( 'level' => '5', 'content' => 'Role' ) ),
	array( 'core/paragraph' ),
	array( 'core/heading', array( 'level' => '5', 'content' => 'Responsibilities' ) ),
	array( 'core/paragraph' ),
	array( 'core/heading', array( 'level' => '5', 'content' => 'Qualifications' ) ),
	array( 'core/list' ),
	array( 'core/heading', array( 'level' => '5', 'content' => 'Highlights' ) ),
	array( 'core/paragraph' ),
)

Which looks like this in the editor:

Post template with ads

Our client is a publisher who needs at least two ads in each post. There’s a few approaches we’ve used in the past:

  • Automatic insertion after X paragraphs. It’s simple to maintain but the ads often don’t follow the natural breaks in article.
  • Manual insertion using a shortcode. The content editor can ensure the ads work well with the content, but it’s more difficult to manage and easy to forget.

With Gutenberg, we simply pre-populate the content area with two ad blocks (built with Advanced Custom Fields) and three paragraph blocks. Content editors can then dive right into content creation around the ad units.

Here’s how you set the block template for posts:

<?php
/**
* Block template for posts
* @see https://www.billerickson.net/gutenberg-block-templates/
*
*/
function be_post_block_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/paragraph' ),
array( 'acf/ad' ),
array( 'core/paragraph' ),
array( 'acf/ad' ),
array( 'core/paragraph' ),
);
}
add_action( 'init', 'be_post_block_template' );
view raw functions.php hosted with ❤ by GitHub

Testimonial block template

We feature testimonials throughout the website, and we have a Testimonial post type for managing them. In the past we would have disabled the editor and added a custom metabox on this post type to collect just the quote and byline.

With Gutenberg, we can limit the editor to just the “Quote” block. This allows the client to use the same UI for managing their blockquotes site-wide.

When registering your post type, use the template parameter to specify an array of which blocks should appear.

Including 'template_lock' => 'all' will prevent any changes to the layout. If you set 'template_lock' => 'insert' it will prevent new blocks from being inserted but still allow the writer re-arrange the existing blocks.

We’ll be featuring these quotes using the “Large” quote style in the theme, so I’ve added is-style-large to the block attributes.

<?php
/**
* Testimonials
*
* @package CoreFunctionality
* @author Bill Erickson
* @since 1.0.0
* @license GPL-2.0+
**/
class EA_Testimonials {
/**
* Initialize all the things
*
* @since 1.2.0
*/
function __construct() {
// Actions
add_action( 'init', array( $this, 'register_cpt' ) );
add_filter( 'wp_insert_post_data', array( $this, 'set_testimonial_title' ), 99, 2 );
}
/**
* Register the custom post type
*
* @since 1.2.0
*/
function register_cpt() {
$labels = array(
'name' => 'Testimonials',
'singular_name' => 'Testimonial',
'add_new' => 'Add New',
'add_new_item' => 'Add New Testimonial',
'edit_item' => 'Edit Testimonial',
'new_item' => 'New Testimonial',
'view_item' => 'View Testimonial',
'search_items' => 'Search Testimonials',
'not_found' => 'No Testimonials found',
'not_found_in_trash' => 'No Testimonials found in Trash',
'parent_item_colon' => 'Parent Testimonial:',
'menu_name' => 'Testimonials',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'supports' => array( 'editor' ),
'public' => true,
'show_ui' => true,
'show_in_rest' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'has_archive' => false,
'query_var' => true,
'can_export' => true,
'rewrite' => array( 'slug' => 'testimonial', 'with_front' => false ),
'menu_icon' => 'dashicons-format-quote',
'template' => array( array( 'core/quote', array( 'className' => 'is-style-large' ) ) ),
'template_lock' => 'all',
);
register_post_type( 'testimonial', $args );
}
/**
* Set testimonial title
*
*/
function set_testimonial_title( $data, $postarr ) {
if( 'testimonial' == $data['post_type'] ) {
$title = $this->get_citation( $data['post_content'] );
if( empty( $title ) )
$title = 'Testimonial ' . $postarr['ID'];
$data['post_title'] = $title;
}
return $data;
}
/**
* Get Citation
*
*/
function get_citation( $content ) {
$matches = array();
$regex = '#<cite>(.*?)</cite>#';
preg_match_all( $regex, $content, $matches );
if( !empty( $matches ) && !empty( $matches[0] ) && !empty( $matches[0][0] ) )
return strip_tags( $matches[0][0] );
}
}
new EA_Testimonials();
view raw cpt-testimonial.php hosted with ❤ by GitHub

There’s no need for writers to include a post title for these quotes, but WordPress’  auto-generated titles weren’t very descriptive.  I’m using the wp_insert_post_data filter to modify the post title to match the value in <cite>. If there is no byline, it sets the title to “Testimonial {ID}”

I don’t like parsing HTML for this data, but it works given the simple content structure. For more advanced layouts I recommend using something like Gutenberg Object Plugin to save the Gutenberg data as an array in the database so you can access it easier.

Nested Templates

You can create nested block templates using container blocks. For instance, here’s an example from the Templates section of the Gutenberg Handbook.

<?php
$template = array(
array( 'core/paragraph', array(
'placeholder' => 'Add a root-level paragraph',
) ),
array( 'core/columns', array(), array(
array( 'core/column', array(), array(
array( 'core/image', array() ),
) ),
array( 'core/column', array(), array(
array( 'core/paragraph', array(
'placeholder' => 'Add a inner paragraph'
) ),
) ),
) )
);
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

    • Metaboxes work exactly the same in WordPress 5.0 as they do in previous versions of WordPress. They will continue to play a role in WordPress for the foreseeable future.

      If you were using metaboxes for content creation because the Classic Editor lacked the features you need, you might be able to now accomplish those goals using the Block Editor instead of building custom metaboxes.

  1. Mr Bill!

    Thanks a bunch fro your Gutenberg posts! I was wondering if you already know a method to implement block templates on a custom page template level. I can’t find anything documentation on it yet. Maybe you had more luck!

Leave A Reply