Progress

Create Custom Gutenberg Blocks in Wordpress Easy Guide

Create Custom Gutenberg Blocks in Wordpress Easy Guide

WordPress 5.0 update was one of the biggest updates in WordPress history. It changed the way WordPress was before that. Blocks were introduced in this update which is very helpful for content creation and best alternatives of page builders. You can also create your own custom Gutenberg blocks as per your needs.

This tutorial is meant to be a simple guide to help you create custom Gutenberg block easily. The official block documentation on WordPress is just another piece of crap for beginners as well as experienced programmers.

Here is an example of AnglePicker Component from WordPress block documentation. There is no preview or image of the component, you need to manually use it in the code and test how it actually looks. The documentation is full of these annoying things.

I have tried to simplify the example for beginners to understand the concept of Gutenberg development.

What are Custom Gutenberg Blocks

Gutenberg blocks
WordPress blocks

Before diving deep into WordPress blocks we need to know what WordPress blocks are?

Blocks exist from WordPress 5.0 to enable smooth visual editing as compare to previous TinyMCE editor.

At first, I thought that Gutenberg was not easy to get comfortable as compared to TinyMCE editor. I started hating it, but all this changed in less than a week.

Gutenberg is far better than the previous WordPress editor, but it takes some time to get comfortable with it.

All elements in the Gutenberg editor including Paragraph, heading and images are blocks.

In reality, blocks are nothing but simple HTML tags enclosed by predefined comments (key-value pair comments as defined by WordPress).

Example:

For a simple paragraph, the HTML will be:

Copy
<!-- wp:paragraph -->
  <p>Some Element of P tag</p>
<!-- /wp:paragraph -->

For Heading the HTML will be:

Copy
<!-- wp:heading -->
  <h2>Some Text of h2 tag</h2>
<!-- /wp:heading -->

Gutenberg blocks are an easy solution and best alternative to page builders.

There are a number of plugins which extends the power of Gutenberg by providing more useful blocks.

Why You need to Create Custom Gutenberg Blocks

Blocks can be very helpful in structuring your content.

Custom Content structure using gutenberg blocks
The custom Content structure of Recipe using Blocks.

If you need custom post type structure then it is a good idea to create your own custom block. It is super easy to create custom Gutenberg block.

For example, I needed custom code block with an optional title and output so I created a custom code block for this site.

There are several blocks examples which you can create to extend the functionality of Gutenberg editor like tabs, accordion, click to tweet, newsletter block, call to action block and so on.

How To Create Custom Gutenberg Blocks

Creating simple Gutenberg blocks is super easy, you just need some basic understanding of React.js and PHP. If you don’t know both then no problem we will explain each and every line of code briefly.

It is recommended to set up a local development environment for this tutorial. You can use flywheel by local for easy setup.

  1. Create an empty folder inside the plugin directory of your local development environment.

2. Create a file named plugin.php with the following content.

Copy
<?php
/**
 * Plugin Name: HolyCoders Tutorial Plugin
 * Author: Digvijay Singh
 * Version: 1.0.0
 * Description: Awesome Plugin to create beautiful blocks.
 */
  
function addMessageBlock() {
  wp_enqueue_script(
    'Message Block',
    plugin_dir_url(__FILE__) . 'message-block.js',
    array('wp-blocks','wp-editor'),
    true
  );
}
   
add_action('enqueue_block_editor_assets', 'addMessageBlock');

Blocks are contained inside plugins so we have created a plugin and defined to add our block (enqueued message-block.js).

We have added an array of two more script dependencies named wp-blocks and wp-editor. The script wp-blocks handles the block registration as we will see later and wp-editor provides useful prebuilt components.

You can read more about wp_enqueue_script()function here.

3. Now add a file message-block.js in the same directory.

Copy
wp.blocks.registerBlockType('hcblock/messagebox', {
  title: 'Message Box',
  icon: 'warning',
  category: 'common',
  attributes: {
    message: {type: "string"},
    backgroundColor: {type: "string"}
  },
  edit: function(props) {
    return React.createElement("div", null, React.createElement("input", {
  type: "text",
  placeholder: "Enter Your Message Here",
  value: props.attributes.message,
  onChange: function onChange(e) {
    return props.setAttributes({
      message: e.target.value
    });
  }
}), React.createElement(wp.components.ColorPicker, {
  value: props.attributes.backgroundColor,
  onChangeComplete: function onChangeComplete(color) {
    props.setAttributes({
      backgroundColor: color.hex
    });
  }
}));
  },
  save: function(props) {
    return wp.element.createElement("div", {
  style: {
    backgroundColor: props.attributes.backgroundColor
  }
}, props.attributes.message);
  }
})

4.) Activate the Plugin.

5.) Find and Use the Block from Gutenberg editor.

Find blocks using its name
Message box Gutenberg block.
Fill the block and hit publish or update.

6.) Publish the post and check its output.

Output of custom gutenberg block.

In-depth explanation of message-block.js Code:

Remember that we passed wp-blocks from plugins.php file (line 13) to our block while registering it, we used it in message-block.js file to register the block.

In the very first line, we register the block. The first parameter of registerBlockType function is a unique name for the block, the general convention is namespace/block-name (all in small case).

Copy
wp.blocks.registerBlockType('hcblock/messagebox', {})

Note: A block name can only contain lowercase alphanumeric characters and dashes, and must begin with a letter.

The second parameter in the registerBlockType function is the object of key-value pair that defines the configuration of the block.

Copy
wp.blocks.registerBlockType('hcblock/messagebox', {
  title: '', //Title to display in Gutenberg editor
  icon: '', // (Optional) icon of block
  description: '', // (Optional) short description about block
  category: '', // Category which block belongs to
  attributes: {},
  edit: function(props) {},
  save: function(props) {}
})

All names are self-explanatory so I will explain attributes, edit and save function which handles all operation of render and save the data.

Attributes: It contains the key-value pairs of data that we want to deal with. Here we are creating Message Box so let us take the message and boxBackgroundColor attribute for simplicity. It will look like this in the code.

Copy
attributes: {
  message: {type: 'string', default: 'This is default Message'},
  boxBackgroundColor: {type: 'string', default: '#EEEEEE'}
}

Edit function: It is a function which describes the render on the backend side (what we see on Gutenberg editor). We define a function which receives props and returns React element (Javascript) to render on the backend side.

Note you can use this online tool to generate React code for the corresponding HTML.

Save Function: It is a function which describes what to render on the frontend (what user see). It should return the instance of WordPress element and should only depend only on attributes and no outside data or logic.

Here is the complete documentation of edit and save function.

You can view all the parameters and their types on the official WordPress blocks documentation.

Create Custom Gutenberg Blocks Using ‘create-Guten-block’

It will be a nightmare to write such code without babel and Webpack because we can’t use the babel online tool each time to write and paste code.

The easy solution to this is create-guten-blocks. It is a toolkit for building WordPress blocks without any complex configuration.

Create-Guten-Blocks toolkit for building Gutenberg blocks

It has Webpack, babel and other necessary tools preconfigured.

If you have used React.js create-react-app then it is similar to that, the only difference is that is build for WordPress block development.

You should go with this method If you are just getting started or you don’t want to configure everything on your own (quite complex).

If you ever feel that the configuration is blocking you from certain features then you can eject to custom setup at any time.

Create WordPress blocks Using Plugins

The easiest way to create Gutenberg blocks. If you hate coding (you shouldn’t) then you must opt this way to easily create useful Gutenberg blocks.

This was my first choice to create custom Gutenberg blocks for this blog because I haven’t worked on PHP. But I didn’t want to increase the load of one extra plugin (this is a complete lie, it was programmer inside me that forced me to start everything from scratch).

There are three plugins which you can use to create Gutenberg blocks easily with very little coding.

LazyBlocks

Lazy Blocks plugin

The best plugin to create Gutenberg blocks for Free. This is the only plugin which is completely free and opensource.

This plugin is just a piece of art.

This should be your first choice if you want to create Gutenberg blocks easily.

Here are some beautiful features of this plugin:

  • More than 20 Control Components
  • Well Documented
  • Custom Templates for Posts and pages
  • PHP and Handlebars support for displaying content
  • Conditional display content
  • Import and export of blocks using JSON

BlockLab

block lab plugin for WordPress

This is another plugin to create Gutenberg blocks. Most of its components are available in the free version but if you want to create some complex block then you need to buy its premium version because some very useful features like Repeater fields are not free.

The features that it offers in premium version are already free in lazy blocks.

ACF – Advanced Custom Field

The most popular plugin to create custom fields. They introduced the feature to create custom Gutenberg blocks in version 5.8.0.

ACF Pro is required to create custom blocks.

Advanced custom fields Gutenberg blocks

It will not be a wise decision to use a sword for sewing purpose. The same thing can be related here, Advanced Custom Fields plugin is used for more complex tasks.

If your website heavily depends on custom content then you should go for ACF.

Conclusion

These were some of the best ways to create custom Gutenberg blocks. Sadly there are not many resources available for Gutenberg development as of now, because it is relatively new and not everyone is ready to accept the Gutenberg update (heavy content websites).

WordPress block documentation is the only way to seek help if you get stuck. Some sections are really well explained while some are crap and require proper explanation and documentation.

I will try to create more tutorials on Gutenberg development.

If you have any confusion or question feel free to ask in comments.

You may also like:

Best managed WordPress Hosting.

Share the Post ;)

Related Posts