23rd March 2019 in Wordpress

Create your own Gutenberg Boilerplate – Part 2

Quick recap: In the previous part of this post, first, we have created a plugin for our Gutenberg Block. Second, installed and configured Webpack and Babel. We are now ready to start writing code for our Gutenberg Blocks.

Step 3: Build the Block

Let’s write the code for our Boilerplate Block.

We created a folder named blocks. We will use this folder to organise all the Gutenberg Blocks we are going to create in this plugin.

Next, create another folder inside the blocks folder, and name it as boilerplate-block. In this folder, we will add code for our block and its styling.

We are creating this folder structure so that we can create individual folders for every block we want to create in this plugin. This will allow us to use the same plugin for creating multiple blocks, keeping the code of each block separate from each other. Later we will be able to simply make a copy of “boilerplate-block” folder to start creating another block in our plugin. 

By now you should have a folder structure like this:
/wp-content/plugins/gutenberg-boilerplate/blocks/boilerplate-block

Here we will create a new file named boilerplate_block.js. This file will have the code for “Boilerplate Block” that we are trying to build.

Note: You can use any name for these files and folders. Just make sure they are easy for you and other developers to recognise later.

Add following code to boilerplate_block.js file: 

const { __ } = wp.i18n; 
const { registerBlockType } = wp.blocks; 

registerBlockType( 'gutenberg-boilerplate/block-boilerplate-block', {

    title: __( 'Boilerplate Block', 'gutenberg_boilerplate' ), 
    icon: 'marker', 
    category: 'common', 
    keywords: [
        __( 'Boilerplate Block', 'gutenberg_boilerplate' ),
        __( 'boilerplate-block', 'gutenberg_boilerplate' ),
    ],

    edit: function( props ) {
        return (
            <div className={ props.className }>
                <p>{ __(`— Hello from the backend.`, 'gutenberg_boilerplate') }</p>
            </div>
        );
    },

    save: function( props ) {
        return (
            <div>
                <p>{ __(`— Hello from the backend.`, 'gutenberg_boilerplate') }</p>
            </div>
        );
    },
} );

To create a new block, we need to use registerBlockType() function. This function take two arguments:

  1. name [string]: “Block names must contain a namespace prefix, include only lowercase alphanumeric characters or dashes, and start with a letter. Example: my-plugin/my-custom-block”
  2. settings [object]: The settings parameter is an object with several predefined properties that must be assigned for your block to work

Note: In addition to creating a simple block, I have used “Template literals” for the text in <p> tags to make it translation ready. It’s always a good idea to make your code translation ready from the beginning.

You can read more about registerBlockType() and Internationalization in Gutenberg documentation.

Following is a stripped down version of boilerplate_block.js file without Internationalisation code, below. You can compare and understand the difference., and you can use this version for your boilerplate if you do not want to add internationalisation support for your blocks.

const { registerBlockType } = wp.blocks; 

registerBlockType( 'gutenberg-boilerplate/block-boilerplate-block', {

    title: 'Boilerplate Block',
    icon: 'marker', 
    category: 'common', 
    keywords: [
        'Boilerplate Block',
        'boilerplate-block',
    ],

    edit: function( props ) {
        return (
            <div className={ props.className }>
                <p>— Hello from the backend.</p>
            </div>
        );
    },

    save: function( props ) {
        return (
            <div>
                <p>— Hello from the backend.</p>
            </div>
        );
    },
} );

Step 4: Make boilerplate_block.js available to webpack

Open /blocks/blocks.js file, and add following line of code in it:

import './boilerplate-block/boilerplate_block';

That’s all we need to do. 

Run npm run dev command on command prompt to compile the code and build /dist/blocks.build.js file.

Step 5: Register & Enqueue Scripts

We need to register and enqueue the script we have created in last step to make this available to WordPress. 

Create a new file init.php in blocks folder. 

We will start by adding the security layer as we did in previous file.

<?php 
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) { exit; }

Next, we need to register and enqueue the script we have created in step 3 and 4 above.

function gutenberg_boilerplate_assets() { 

    // Register our block script with WordPress
    wp_register_script(
        'gutenberg-boilerplate-block-js',
        plugins_url( '/dist/blocks.build.js', dirname( __FILE__ ) ), 
        array( 'wp-blocks', 'wp-i18n' ), 
        filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.build.js' ), 
        true 
    ); 

    // Enqueue the script in the editor
    register_block_type('gutenberg-boilerplate/blocks', array(
        'editor_script' => 'gutenberg-boilerplate-block-js',
    ));
}

add_action( 'init', 'gutenberg_boilerplate_assets' );

Here we are creating a new function gutenberg_boilerplate_assets() and initialising this function via init action hook. 

Inside this function, I have used wp_register_script() to register the script that we have prepared after processing it via webpack

Note that we have added two dependencies wp-blocks and wp-i18. While registering the script, we have used functions from these dependencies at the top of boilerplate_block.js file.

And we have enqueued the script using register_block_type() function, to make it available in Gutenberg editor. 

Later we will use these functions to register and enqueue CSS files also. 

Step 6: Activate the plugin and test the block

Our new “Boilerplate Bock” is ready for testing. 

Go to Settings > Plugins and activate the plugin “Gutenberg Boilerplate”

Create a new page or post, and try adding a new block. Search for “Boilerplate Block” and select it. 

Boilerplate Block
Boilerplate Block in Editor

Publish or Preview the page, to see the block on Frontend. 

Boilerplate Block in Frontend 
(Twenty Nineteen Theme)

Congratulations! your new shiny block is working. 

One last final piece we are missing here is CSS. We will take a look at how to add CSS files in the next part of this series.

About the author

Alok Jain

Alok design digital experiences to help businesses achieve their goals. He is passionate about designing right User Experience for their customers. For over 15 years, he have worked with small startups to mature product teams. Whether it is designing a WordPress product, a frontend experience, WooCommerce, Shopify, he follow the best product development practices for design and code, for desktop or mobile.