Day 26: Building Custom Templates in Gutenberg

Introduction

Welcome to Day 26 of the Gutenberg development series! Today, we’ll focus on custom templates, which allow you to define the structure of a post or page. By providing predefined templates, you can ensure that specific content layouts are consistent across your website. This is especially useful for custom post types, landing pages, and specific layouts that require a particular block structure.

In this guide, you’ll learn how to:

  • Create and register custom templates for posts and pages.
  • Define block layouts that users can start with.
  • Use custom templates with custom post types for better content management.

What are Custom Templates in Gutenberg?

Custom templates in Gutenberg allow you to define the default structure of a page or post using blocks. This ensures that users start with a specific layout, making content creation faster and more consistent. For example, you might create a template for a portfolio post type that includes a featured image, gallery, and testimonial sections.

Custom templates are especially valuable for:

  • Custom Post Types: Use predefined templates for specific content types like portfolios, testimonials, or products.
  • Landing Pages: Create consistent layouts for sales or marketing pages.
  • Content Structure: Ensure that certain elements like headers, images, or call-to-action blocks are always included in specific pages.

Step 1: Creating a Basic Custom Template for Pages

Let’s start by creating a custom template for About pages, with predefined blocks for a heading, an image, and a text area.

  1. Register the Custom Template

In your theme’s functions.php file or a custom plugin, use the register_post_type function to add a template to the default Page post type.

function my_theme_register_custom_templates() {
    $post_type_object = get_post_type_object( 'page' );
    if ( ! $post_type_object ) {
        return;
    }

    $post_type_object->template = array(
        array( 'core/heading', array(
            'placeholder' => 'Enter your page title...',
            'level' => 1,
        ) ),
        array( 'core/image', array() ),
        array( 'core/paragraph', array(
            'placeholder' => 'Add a description or introduction here...',
        ) ),
    );

    $post_type_object->template_lock = 'all'; // Prevents users from removing required blocks
}
add_action( 'init', 'my_theme_register_custom_templates' );

Explanation:

  • Template: The template parameter defines an array of blocks that will be added by default when creating a new Page. This template includes a Heading, an Image, and a Paragraph.
  • template_lock: The 'all' value locks the template, preventing users from removing the blocks but still allowing them to edit the content.

Step 2: Using Custom Templates with Custom Post Types

Custom templates are even more powerful when used with custom post types. Let’s create a Portfolio custom post type that includes a predefined template for showcasing projects.

  1. Register the Portfolio Custom Post Type

Add the following code to register the Portfolio post type with a custom template:

function my_theme_register_portfolio_post_type() {
    register_post_type( 'portfolio', array(
        'label'         => __( 'Portfolio', 'my-theme' ),
        'public'        => true,
        'has_archive'   => true,
        'show_in_rest'  => true,
        'supports'      => array( 'title', 'editor', 'thumbnail' ),
        'template'      => array(
            array( 'core/heading', array(
                'placeholder' => 'Project Title',
                'level' => 2,
            ) ),
            array( 'core/image', array() ),
            array( 'core/paragraph', array(
                'placeholder' => 'Write a brief overview of the project...',
            ) ),
            array( 'core/gallery', array() ),
            array( 'core/quote', array(
                'placeholder' => 'Client testimonial here...',
            ) ),
        ),
        'template_lock' => 'insert', // Users can add more blocks but can't remove the predefined ones
    ) );
}
add_action( 'init', 'my_theme_register_portfolio_post_type' );

Explanation:

  • Portfolio Post Type: Registers a new post type called Portfolio.
  • Template: Predefines a layout with a Heading, Image, Paragraph, Gallery, and Quote block.
  • template_lock: The 'insert' value allows users to add new blocks but prevents them from removing the default template blocks.

Step 3: Modifying Templates in the Block Editor

Users can modify the predefined templates when creating or editing a post if the template is not locked. Let’s adjust the template lock settings for more flexibility.

  1. Adjust Template Lock for Flexibility

Update the template lock setting to allow users to remove blocks if needed:

'post_type_object->template_lock = false;'

Explanation:

  • No Lock: By setting template_lock to false, users can remove or rearrange blocks, providing them with complete flexibility while still starting with a suggested structure.

Step 4: Testing Custom Templates in the Editor

After registering custom templates, it’s important to test them in the Block Editor.

  1. Rebuild Your Theme:
    • Ensure your theme or custom plugin is active with the updated template code.
  2. Test in the Editor:
    • Create a new Page or Portfolio post.
    • Verify that the predefined blocks are automatically added when creating the new post.
    • Edit the content to ensure that it’s user-friendly and meets the design needs.
  3. Check the Front-End Display:
    • Preview the post or page on the front end to see how the template layout appears to visitors.

Step 5: Exporting Templates for Use on Other Sites

You can export custom templates to reuse them on other WordPress sites.

  1. Export Template as JSON
    • Copy the template array code from your functions.php or custom plugin and save it as a JSON file.
    • To import the template on another site, paste the JSON into the new site’s functions.php or custom plugin.

Best Practices for Custom Templates

  1. Use Templates for Consistency: Use custom templates to ensure that specific content elements remain consistent across posts or pages, such as header structures or promotional sections.
  2. Lock Templates Appropriately: Use template_lock when you need to enforce certain layout elements, and leave it unlocked when flexibility is more important.
  3. Organize by Post Type: Define different templates for various custom post types to tailor content creation for each type.

Conclusion: Simplifying Content Creation with Custom Templates

Custom templates are a powerful feature in Gutenberg that streamline the content creation process by providing a predefined starting point. Whether you’re building templates for custom post types, landing pages, or specific content layouts, they help maintain consistency and save time for users.

In this article, you’ve learned how to:

  • Create and register custom templates for posts and pages.
  • Use templates with custom post types to provide structured content.
  • Adjust template lock settings for more flexibility in the editor.

In Day 27, we’ll explore custom block collections, where you can group related blocks together for better organization in the Block Editor.


Leave a Reply

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