Image of building blocks
Photo by Ryan Quintal on Unsplash

Create a Custom Gutenberg Editor Block in Wordpress

bshelling
6 min readMar 31, 2020

--

Easily create a custom block in just a few steps

The Gutenberg editor in Wordpress has become a problem child for WP users and developers across the community. While it has its pros and cons it can easily be seen as Wordpress’ greatest innovation. Its primary use is to make content creation easier when it comes to building unique page layouts and designs. This feature is something Wordpress lacked for a long time especially when it’s already implemented in other frameworks such as Drupal or CraftCMS.

With any new feature as a developer comes the pain of understanding how it works and how to extend it. In previous versions of Wordpress, extending the platform was mostly done using PHP. Now with the Gutenberg editor, it requires a mix of modern Javascript using nodejs and PHP to develop on the editor.

Before you develop a custom block I recommend reading about how blocks work within the Gutenberg editor.

The plan will be to create a block that displays a headline, sub-headline, an image (optional) and a call to action (optional)

Overview

This diagram describes the development lifecycle for block creation.

Project setup

To begin, create a new folder in the plugins folder that will house the custom block.

$ mkdir hmsection-block
$ cd hmsection-block

Within the home section block folder add index.php. This file will be the entry point for the plugin. In the index.php file add this code to create the plugin. Once the code is added go to the plugins section and activate it.

<?php
/**
* Plugin Name: Homepage Section Block
* Plugin URI: https://myhomepagesection.example
* Description: Homepage sections for Wordpress
* Version: 1.0
*/
Screenshot showing home section block plugin
Activate Home Section Block Plugin

Extending the Gutenberg editor requires the use of Node packages. This block will require a few packages that will be added as it’s being built and will also live in the hmsection-block folder. Create a package.json file within this folder.

{
"name": "hmsection-block",
"version": "1.0.0",
"description": "Homepack section block",
"main": "index.js",
"author": "bshelling",
"license": "MIT"
}

The first packages to add are wordpress/scripts and wordpress/blocks. The scripts package has build scripts that help with transpiling the code into javascript that browsers can support. The blocks package provides functions for building the blocks within the editor.

The additional package added is node sass. Node sass will allow stylesheets to be compiled and add into a separate folder. A index.js file within the src will need to be added to execute the build.

Add these packages.

$ yarn add @wordpress/scripts @wordpress/scripts --save-dev
$ yarn add noda-sass --save-dev

To build scripts using this package requires the wp-scripts and node-sass commands. Add the command to the scripts block within the package.json file.

Note for the node-sass there are options to be considered before executing. The location of the file needed for compiling include path (the location of the original file) and o (output directory).

{
"name": "hmsection-block",
"version": "1.0.0",
"description": "Homepage section block",
"main": "index.js",
"author": "bshelling",
"license": "MIT",
"scripts": {
"build": "wp-scripts build && node-sass --include-path sass src/sass/hmsection-block-style.scss -o build/css",
"dev:watch": "wp-scripts start && node-sass --include-path sass src/sass/hmsection-block-style.scss -o build/css -w"

},
"devDependencies": {
"@wordpress/scripts": "^7.1.3",,
"node-sass": "^4.13.1"

},
"dependencies": {
"@wordpress/blocks": "^6.12.3"
}
}

Go ahead and test the build

$ yarn build

When the build is complete, a build folder will be added with a few files and a folder added. Files and folder include:

build
-- css
-- hmsection-block-style.css
index.asset.php
index.js
index.js.map

Notice the index.asset.php file, this file include the build version and the required dependencies needed to load the build. To load the build it’s needs to be enqueued using wp_register_script() to load the javasript file and wp_register_style() to load the stylesheet.

-- index.php --function hmPageSectionBlock(){$buildAssets = include(plugin_dir_path(__FILE__)).'build/index.asset.php';/**
* Editor Script
*/
wp_register_script(
'hmsb-editor-script',
plugins_url('build/index.js',__FILE__),
$buildAssets['dependencies'],
$buildAssets['version']

);
/**
* Editor Style
*/
wp_register_style(
'hmsb-editor-style',
plugins_url('build/css/hmsection-block-style.css',__FILE__),'',
$buildAssets['version']

);
/**
* Register block
*/
register_block_type('bshelling/hm-section-block',array(
'editor_script' => 'hmsb-editor-script',
'editor_style' => 'hmsb-editor-style'

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

Register Block Type

With the build setup complete, the styles and scripts enqueued, the next step is to register the block. This is the only way the block will be available within the editor. If we revisit the comp the block will display a headline, subheadline, an image (optional) and a call to action (optional).

There are packages that will be imported to create these fields. For now we will hardcode the comp then implement the editable fields later.

Registering a block type requires importing registerBlockType from the wordpress/blocks package. Add this package to the package.json

$ yarn add @wordpress/blocks

When creating a custom block it’s important that its name is uniques and the block settings are added according to the requirements. For this example the block settings will be the title, description, icon, category, edit. The category is property is related to the grouping of blocks within the editor. This block will exist in the layout category. The edit property is a function that returns a visual representation of block on the backend.

Image of block categories
Block Categories

Within the src folder create index.js and block.js files. From there import the import registerBlockType in block.js. Index.js is used for build execution and clean code, in this case block.js is being imported.

-- src/block.js --import { registerBlockType } from '@wordpress/blocks';const homeBlock = <div className="homepage-section-block"><h1 className="title">Headline</h1><p className="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce in dui sapien. Donec tincidunt diam in libero porttitor, quis feugiat diam mollis.
</p><button>Read More</button></div>;
registerBlockType('bshelling/hm-section-block',{
title: 'Homepage Section Block',
description: 'The copy section is for use on the homepage',
icon: 'text',
category: 'layout',
edit: function(){
return (homeBlock);
},
save: function(){
return (homeBlock);
}
});

The html representation of the block is assigned to a variable, returned within the edit and save functions. Because the block is written with JSX syntax, the html will be compiled during the build. Again execute the build.

$ yarn build

After a successful build the new block should be available within the block modal and can be added to the editor. Also when the page is published the block should be available on the frontend.
Note, when viewing the block on the frontend the styling may not show up because a stylesheet hasn’t been added when the block was registered.

Image of custom block available within block modal
Custom Block available
Homepage Section Block
Homepage Section Block

Be on the lookout for another article taking this a step further by making the block editable, adding an image, changing colors, alignment and more.

Block creation files

--

--

bshelling

Shelling is what they call me. A forward thinker debugging life's code line by line. Creator, crossfitter, developer, engineer