PHP ROUTE

How to Create Gutenberg Custom Block Patterns in WordPress

Gutenberg is constantly evolving and more new and better features are being added to make the content creation experience faster, smoother, and better. And Block Patterns are one of the most useful and amazing additions to the Gutenberg functionality. It makes content creation and content reusability a whole lot easier. And I am sure that once you learn how to make them, you’ll fall in love with them.

In this article, we are going to learn how we can code our own custom block patterns and add them to our WordPress website using a plugin. So let’s start with the basics and know what exactly are block patterns.

What are Block Patterns?

Now let’s jump to the main question what are block patterns? we have talked about patterns before and how you can create block patterns without code in one of our previous articles read it here. But as a refresher, Block Patterns are premade, ready-to-use layouts for WordPress made out of Gutenberg Blocks. Basically, you save multiple blocks together in one file or say code and reuse it across the website.

Block Patterns can have pretty much any design element or say block inside of them. For example, you can have images, rows, columns, text, buttons, and so on inside a block pattern. The best part once you created a block pattern you can use it almost anywhere on your website. You can make changes to it, you can add more blocks into it or remove any, or you can redesign the whole thing.

Or not just on your website you can use these patterns on any other websites as well. You can simply just copy and paste a pattern on the other website with no extra steps or anything but there’s a catch though we will talk about it later in this article.

Now to use a block pattern we can either use them straight from the block editor or can copy a pattern from a third-party website and paste it straight into our block editor. You can see that in action in this article.

Now we know what patterns and how to use them let’s know how to develop them.

First, Look at the Block Pattern API

Before building a custom block pattern first we need to learn about Block Pattern API. To build a custom block pattern it is required to use WordPress Pattern API so we can register our custom block patterns and custom block patterns categories into block editor.

To register custom block patterns or block patterns categories we will use Block API functions. We can use them in our theme’s function.phpfile or we can create a separate plugin as well. If you are not using any child theme or even in general using a plugin is always recommended so we will be focusing on creating it via plugin you can paste the same PHP code in your function.phpto tie it up with your theme if you want.

One thing to know is that while registering a block pattern we will be using raw HTML within PHP. That means we need to modify our HTML and things like quotes must be escaped. Doing this step manually especially when we are using multiple blocks or complex layouts is a nightmare. Thankfully there is an automated tool called Code Beautify that can help us a lot.

Building Custom Block Pattern

Enough theories! now let’s start the practical and start coding our own custom block pattern. To register our block pattern we will be using the register_block_pattern()function from Block API. But before that, we need to block out the pattern first (i.e design the block pattern in block editor).

Step 1: Create the Block Pattern

The first step to build a custom block pattern to create a block pattern inside the block editor, just create a new page or post on your website and create a design you want to add to your pattern. There is no limit on how many blocks you can use inside one pattern you can use as low as one to as many as you want.

custom block pattern

For our use case, I have created the pattern you are seeing in the image above. It has a heading at the top, three images below the heading, a paragraph below the images, and a button below the paragraph. The main idea behind making a block pattern is to create something you wanna use multiple times on your website, creating something for single use is pointless so keep that in mind while creating a pattern.

Note: While creating block patterns one thing to keep in mind is if you want your pattern to be used on multiple websites then make sure to only use the blocks available in the official WordPress Gutenberg Block Editor not the third party blocks or install the third-party block provider plugins to the sites where you’ll be using the pattern. Because sometimes these blocks rely on the stylesheet available inside the third-party plugins so if blocks get loaded but didn’t have the stylesheet then they might break.

Step2: Copy the Block Pattern

Now after creating our block in a way we want, it’s time to copy its content. Thankfully this task is much easier than it sounds.

To copy its content first select the blocks you want to copy. To select multiple blocks press Shift on the keyboard and select the blocks you want to have in your pattern(tip: while pressing shift select the top and bottom block everything inside them will be selected automatically).

Now after selecting the blocks you want, click on the three-dot menu as pointed with 1 in the image above and then click on the copy as point 2 highlights.

If you now paste the copied content in a text editor the result will look like this:

<!-- wp:heading {"textAlign":"center"} -->
<h2 class="has-text-align-center">I Love Cats</h2>
<!-- /wp:heading -->

<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column -->
<div class="wp-block-column"><!-- wp:image {"id":46,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image size-full"><img src="https://webprotime.store/wp-content/uploads/2021/10/alvan-nee-ZCHj_2lJP00-unsplash.jpg" alt="" class="wp-image-46"/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->

<!-- wp:column -->
<div class="wp-block-column"><!-- wp:image {"id":50,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://webprotime.store/wp-content/uploads/2021/10/mathieu-odin-YeQIAysCP3w-unsplash-683x1024.jpg" alt="" class="wp-image-50"/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->

<!-- wp:column -->
<div class="wp-block-column"><!-- wp:image {"id":49,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://webprotime.store/wp-content/uploads/2021/10/karina-vorozheeva-rW-I87aPY5Y-unsplash-2-683x1024.jpg" alt="" class="wp-image-49"/></figure>
<!-- /wp:image --></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">Research has proven that petting a cat causes a release of the <strong>“love hormone”</strong> in humans.</p>
<!-- /wp:paragraph -->

<!-- wp:buttons {"contentJustification":"center"} -->
<div class="wp-block-buttons is-content-justification-center"><!-- wp:button {"width":75,"className":"is-style-fill"} -->
<div class="wp-block-button has-custom-width wp-block-button__width-75 is-style-fill"><a class="wp-block-button__link">Watch More Cats</a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

Step 3: Escape the Code

As I have mentioned previously we need to escape our HTML so we can parse it into our PHP to make it work with Block Pattern API.

Now if your block is small you can escape it manually, but I prefer to use the “JavaScript Escape Unescape” tool by Code Beautify. Just go to this link paste the copied code you’ll get the output as an escaped string. Copy that output string, the string will look like the code given below.

<!-- wp:heading {\"textAlign\":\"center\"} -->\n<h2 class=\"has-text-align-center\">I Love Cats</h2>\n<!-- /wp:heading -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":46,\"sizeSlug\":\"full\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-full\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/alvan-nee-ZCHj_2lJP00-unsplash.jpg\" alt=\"\" class=\"wp-image-46\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":50,\"sizeSlug\":\"large\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-large\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/mathieu-odin-YeQIAysCP3w-unsplash-683x1024.jpg\" alt=\"\" class=\"wp-image-50\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":49,\"sizeSlug\":\"large\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-large\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/karina-vorozheeva-rW-I87aPY5Y-unsplash-2-683x1024.jpg\" alt=\"\" class=\"wp-image-49\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->\n\n<!-- wp:paragraph {\"align\":\"center\"} -->\n<p class=\"has-text-align-center\">Research has proven that petting a cat causes a release of the <strong>“love hormone”</strong> in humans.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:buttons {\"contentJustification\":\"center\"} -->\n<div class=\"wp-block-buttons is-content-justification-center\"><!-- wp:button {\"width\":75,\"className\":\"is-style-fill\"} -->\n<div class=\"wp-block-button has-custom-width wp-block-button__width-75 is-style-fill\"><a class=\"wp-block-button__link\">Watch More Cats</a></div>\n<!-- /wp:button --> </div>\n<!-- /wp:buttons -->

Now our code is properly tidied up and ready let’s jump to the next step.

Step 4: Register the Custom Block Pattern

Now we will register our block pattern using a new plugin, if you know how to create a new plugin then create a plugin file. Here we will take leverage of register_block_pattern()of Block Pattern API. In this function, we will pass the name of the pattern as the first argument and in the second argument, we will parse an array with pattern configurations.

In the name of the block pattern, it is recommended to use the namespace with the name to avoid conflicts with other patterns with the same name. For example, our cat block pattern will be named like wpt/cat-block-pattern.

In the second config array, we can add multiple things title, content, description, categories, keywords, viewportWidth. The title and content are required and the rest of the parameters are optional. You can read more about them in the Block API documentation.

So with plugin code and the register_block_pattern()our complete PHP code will be like the code shown below:

<?php 

/*
Plugin Name: Webprotime Custom Block Patterns
Description: Custom cat block pattern for Gutenberg block editor.
Version: 1.0
Author: Webprotime team
Author URI: https://www.weprotime.com
*/

function my_custom_wp_block_patterns() {

    register_block_pattern(
        'wpt/cat-block-pattern',
        array(
            'title'       => __( 'Cat Block Pattern', 'cat-block-pattern' ),
                        
            'content'     => "<!-- wp:heading {\"textAlign\":\"center\"} -->\n<h2 class=\"has-text-align-center\">I Love Cats</h2>\n<!-- /wp:heading -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":46,\"sizeSlug\":\"full\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-full\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/alvan-nee-ZCHj_2lJP00-unsplash.jpg\" alt=\"\" class=\"wp-image-46\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":50,\"sizeSlug\":\"large\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-large\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/mathieu-odin-YeQIAysCP3w-unsplash-683x1024.jpg\" alt=\"\" class=\"wp-image-50\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image {\"id\":49,\"sizeSlug\":\"large\",\"linkDestination\":\"none\"} -->\n<figure class=\"wp-block-image size-large\"><img src=\"https://webprotime.store/wp-content/uploads/2021/10/karina-vorozheeva-rW-I87aPY5Y-unsplash-2-683x1024.jpg\" alt=\"\" class=\"wp-image-49\"/></figure>\n<!-- /wp:image --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->\n\n<!-- wp:paragraph {\"align\":\"center\"} -->\n<p class=\"has-text-align-center\">Research has proven that petting a cat causes a release of the <strong>“love hormone”</strong> in humans.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:buttons {\"contentJustification\":\"center\"} -->\n<div class=\"wp-block-buttons is-content-justification-center\"><!-- wp:button {\"width\":75,\"className\":\"is-style-fill\"} -->\n<div class=\"wp-block-button has-custom-width wp-block-button__width-75 is-style-fill\"><a class=\"wp-block-button__link\">Watch More Cats</a></div>\n<!-- /wp:button --></div>\n<!-- /wp:buttons -->",
            
            'categories'  => array('header'),
        )
    );

}    
add_action( 'init', 'my_custom_wp_block_patterns' );

In the above code, we have created a plugin called Webprotime Custom Block Patterns. Just create a PHP file with the above code and add it to /wp-content/plugins/ folder. Then make activate the plugin to make it work.

After adding the above code our block pattern will be added and accessible via block editor on any post or page. You can see our working pattern in the video below.

You may have noticed above we have used ‘header’ as a category, and that is one of the default categories given by WordPress. But what about adding our own category? well, next we are going to learn that.

Custom Block Pattern Category

If you are building multiple patterns or a theme developer having a custom block category is very useful. So let’s see how we can do that. To add a custom block category we will use register_block_pattern_category()function or Block Pattern API.

This function expects two parameters first the name of the category and second an array with the configuration or the category. For now, in the category config array only labelcan be added.

The PHP code of adding a new category will be like the one shown below:

function wpt_register_block_categories() {

    register_block_pattern_category(
        'wpt-category',
        array( 'label' => _x( 'WPT Category', 'my plugin', ) )
    );

}
add_action( 'init', 'wpt_register_block_categories' );

Now our category will be added, don’t forget to change the category name in the register_block_pattern()function.

Conclusion

Now we have learned how we can code our own custom block pattern and use it on our website. We have also taken a look at how we can add our own categories for our custom block patterns. As always do make your own block pattern.

If you face any issues while following our tutorial or has any doubts, questions or suggestions do share them with us in the comments below we will try to respond as soon as possible.

Have questions or confused about something WordPress Related? Join Our Discord Server & ask a Question

Leave a Comment

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

Scroll to Top