Kid playing with blocks

Neither the constant growth in the amount of websites that choose WordPress nor its dominant position in the market have made the WordPress development community relax. WordPress is going to change a lot in a very short time. And the biggest change in WordPress is called Gutenberg.

In this article I’m going to talk about Gutenberg and I’m going to show you how to get involved in its development by creating your first block, a concept that you will certainly have to master if you plan to continue earning a living with WordPress for years to come. Let’s get started!

What is Gutenberg?

Gutenberg is the new content editor for WordPress. But it’s much more than that. Gutenberg will change the way users and developers work with WordPress.

So far you’ve used WordPress‘ editor as if it were a Microsoft Word document. Well, this is about to change as the concept of block appears on the scene. Now your WordPress content will be composed of blocks—you’ll have blocks for paragraphs, images, headers, quotes, and more. In addition, the developer community will go crazy by creating plugins that add new custom blocks.

If you want a first glimpse of Gutenberg’s look, don’t miss the following video where Matías Ventura, the lead developer of Gutenberg, demoed its main features during the past WordCamp US 2017:

Also, keep in mind that Gutenberg won’t only be the editor in WordPress—in future development iterations, the block concept will replace other familiar concepts in WordPress such as widgets and menus. Soon WordPress will be all blocks. And that’s why I’m interested in teaching you how to create a basic block today.

Install and Activate Gutenberg

It’s said that Gutenberg will be ready to be included in WordPress version 5.0 by April 2018. But I think we’re gonna have to wait a little longer until Gutenberg ends up inside WordPress.

Right now if you want to try Gutenberg you will have to install a plugin. But be careful, I don’t recommend you to do it in your production WordPress installation, since it’s still under development and you can break things. Try it in a test installation instead.

Screenshot of the Gutenberg editor.
Screenshot of the Gutenberg editor.

Just install the Gutenberg plugin, activate it, and go to edit a post or page. By the way, I’d love to hear your opinion after testing it, as there’s been a lot of controversy with all this ?

Let’s Create a New Block for Gutenberg

Now that you know what Gutenberg is, let’s get our hands dirty and code some stuff, shall we? To do this, we are going to create a new block for Gutenberg that allows us to add a customer testimonial on our website. The testimonial will include a photo of the person, his or her name and position, as well as the text of the testimonial itself. The final result we want will look like this:

Mockup of the new testimonial block we want to add to WordPress.
Mockup of the new testimonial block we want to add to WordPress.

Let’s make it work!

Creation of The Plugin and Its File Structure

First of all we will create a plugin for WordPress that includes the necessary files to have a new block in Gutenberg. To do this, create a structure of files and folders like the following:

File structure for the plugin that adds the testimonial block in Gutenberg.
File structure for the plugin that adds the testimonial block in Gutenberg.

Here’s what you should know about these files:

  • block/testomonial/index.php is responsible for enqueueing the files that define the block and displaying it in both the backend and the WordPress frontend.
  • block/testimonial/block.js defines the testimonial block itself and its behavior when editing and saving it. It’s the most important “Gutenberg-related” file in regarding the block.
  • block/testimonial/editor.css contains CSS rules for styling the blog in the Gutenberg editor.
  • block/testimonial/style.css contains CSS rules for styling the blog in the frontend, when a user accesses your site and views the final result.
  • nelio-testimonial-block.php is the plugin‘s main file, where you define the headers needed to describe the plugin and include the previous index.php file. If you’ve ever created a WordPress plugin, you’re already familiar with it. You can see it here.

You’ll find all the code of the testimonial block in GitHub.

Enqueue the Necessary Files

Once you’ve created the files and the structure of the plugin‘s working, you simply need to enqueue both the CSS and JavaScript files required by Gutenberg. Just tweak block/testomonial/index.php so that it looks as follows (see it in GitHub):

Note that we basically use two hooks: enqueue_block_editor_assets and enqueue_block_assets. The first hook is for including the files we use within the Gutenberg editor: block.js and editor.css. It’s also worth noting that block.js file has some dependencies (wp-blocks, wp-i18n, and wp-element), which are necessary if you want to create a block like ours and internationalize it. The second hook simply enqueues the frontend styles: style.css.

Register The New Block

Now let’s take a closer look at block.js (link to the file in GitHub). First of all, we have to register the new testimonial block, which can be easily done by using Gutenberg’s registerBlockType method:

That’s a lot of code, isn’t it? But don’t panic, I”m gonna explain it step by step. First we name the block using a unique, internal identifier. In our case, this name is 'nelio/testimonial-block'. Then, we simply pass an object with all the relevant properties of the block. For instance, there’s a title (line 10), an icon (line 13), a block category (line 16), and some extra attributes (lines 19 to 47). Easy, right? ?

Attributes are the characteristics that the block will contain. In our case, the testimonial block will have the following:

  • name: name of the person who writes the testimonial.
  • position: job of that person.
  • testimonial: the text of the testimonial.
  • mediaID: ID of the image in the WordPress media library.
  • mediaURL: URL of the image of the person.
  • alignment: arrangement of the text in the testimonial.

One important thing to keep in mind is the following: any attribute that has an HTML element associated with it needs a unique selector, or Gutenberg will give you an error when opening the content. Thus, if for example we have several attributes that are associated with <p> tags inside the block, we must have a different selector for each one (you can do it with different CSS class names).

Finally we have the editing and saving functions of the block. Let’s take a closer look at them both!

The edit Method

This is where the good stuff starts. The edit method allows you to get the block ready for editing within Gutenberg. Basically, this method returns a React component formed by all the components that we want to appear in the editor. It looks like this:

It looks very complicated, but trust me, it isn’t—they’re only a bunch of React components. Essentially, we create the HTML structure by nesting elements with the function el(). For example, if you look at lines 79 to 91, you will see that we define the <p> tag containing the position of the person making the testimonial. We define the class of the element (nelio-testimonial-position), a placeholder to show (Position, which is translatable), the value of the element (which we take from the previously-defined block attributes), and the onChange and onFocus functions (to update the value of the attribute and control its focus). This pattern repeats over and over again.

There are, however, some additional peculiarities. For instance, there’s a button to open the image selector of the media library on lines 37 to 47. This uses blocks.MediaUpload, a reusable component of Gutenberg himself. In lines 22 to 30 we also reuse another another reusable component: the bar where you can change the alignment of the text.

The save Method

The save method is in charge of taking the information of the block and preparing it to save it in the database. It’s a lot easier than the edit method and looks like the following:

Notice that we built a div element that contains two more divs inside. The first has the image of the testimonial and the second the three paragraphs with the text of the testimonial, the name of the person who says the testimonial, and his position.

Styling the Block

If we do nothing else, the result in the editor is not very pretty (but, hey, it works!):

Block for the testimonial without CSS styles for the editor (editor. css is empty).
Block for the testimonial without CSS styles for the editor (editor.css is empty).

which looks as follows when we add some real data:

If we add content to the block, we see that the image makes everything overflow. There are no CSS styles defined.
If we add content to the block, we see that the image makes everything overflow. There are no CSS styles defined.

And if we publish the post, this is what our visitors see:

What our visitors see is not what we wanted in our initial mockup. We must use CSS because style.css is empty.
What our visitors see is not what we wanted in our initial mockup. We must use CSS because style.css is empty.

To improve the way this block  looks and make it more user friendly we need to add some styles. Remember those files we enqueued at the beginning? Exactly, we’re talking about the editor.css and style.css files! Well, it’s time to tweak them so that things look beautiful.

After a few minutes (you can view the final result of both files in GitHub), the block in Gutenberg finally looks like this:

By adding CSS to the editor.css we can achieve something much more similar to what we had sketched in our mockup.
By adding CSS to the editor.css we can achieve something much more similar to what we had sketched in our mockup.

and this is how it looks in the frontend:

Visitors to our website will see the block correctly when we add the appropriate CSS styles to style.css.
Visitors to our website will see the block correctly when we add the appropriate CSS styles to style.css.

Closing Remarks

Creating a new block in Gutenberg can be complicated, but it’s easier than expected if you go step by step. Once you’ve encoded the basic stuff, you only need to work with three files, basically.

The first is a JavaScript file where you define the block itself, its attributes, and the save and edit methods. This is the most complicated part. In our example we have used basic JavaScript, but it’s easier if we use JSX syntax to define React components. If you want me to, we can refactor the testimonial block using JSX in a future post. ? Let me know in the comments section!

The other two important files are those that define the styles of both the editor and the frontend: editor.css and style.css. You have already seen that a little bit of CSS can give a radical change to the final result. I encourage you to test the code and improve it.

Resources

Before I finish, let me leave you with a list of interesting resources in case you want to learn more about Gutenberg. Remember that Gutenberg will arrive soon, and we should be ready for it!

Featured Image by Caleb Woods on Unsplash.

17 responses to “How to Create Your First Block For Gutenberg”

  1. zakoops Avatar
    zakoops

    After several readings on the subject of Gutenberg, I realized my epiphany on the whole concept of blocks after your post and I thank you for it!

    But before investigating further, my big question for now is what is the ideal way for creating blocks: with classic ES5 JavaScript (like you do in this post) or with the whole shebang (webpack, React, ES 6/7/8/Next, ESLint, Babel, etc.), with the hassle of dealing with multiple installations, complexities, versioning, and what else?

    Since the first goal of a block is to be displayed with simple html and css, the webpack, React and Babel machinery required behind the scene seems simply disproportionate. In this light, your proposal for refactoring the testimonial block using JSX in a future post could be still quite interesting and, importantly, how would you feel about the whole experience, comparing both methods.

    1. Antonio Villegas Avatar

      Hi zakoops! Thanks for your kind words. The point here is that developing your blog using all the JavaScript utilities would simplify the code (JSX is easier to read and understand than plain JavaScript when writing blocks) but the setup is more complex. Fortunately, there are utilities like the one from Ahmad Awais here that simplify the whole process. About the refactoring, I plan to do it in a future post. Stay tuned 😉

  2. Chris Avatar
    Chris

    Thank you for that great tutorial!

    Could you give me a hint how to transform a shortcode into a Gutenberg block? I understand that the shortcode parameters could be saved to the database with the “save” method. But how is that information later retrieved when rendering that block on the frontend and how would I call the PHP method that renders the actual shortcode content? The HTML cannot already be rendered in the editor, it should be dynamically created when someone views the page.

    I noticed that there is a “shortcode” block, which I could modify. But this block still seems to rely on shortcodes, and since they will be retired in future, I am searching for a “Gutenberg way” to go about it. Thanks!

    1. Antonio Villegas Avatar

      Hi Chris. The edit method deals with the way in which you display the block in the editor and the save method deals with the way the block is stored (as HTML) in the post content. Read the full example and try to execute it in your local WordPress installation. After that, you’ll probably get a basic idea of how it works. That way you’ll be able to replicate the shortcode behavior as a block.

      1. Chris Avatar
        Chris

        Thanks for your speedy reply! I got it now working with register_block_type()

        https://wordpress.org/gutenberg/handbook/blocks/creating-dynamic-blocks/

  3. Lukas Avatar

    Hello, thank you for your tutorial.
    I just tried it but in backend I get the following issue: https://drive.pp.works/index.php/s/KXfw9ZjB8kaaNEc

    Only in the frontend the element gets displayed correctly (just the border of it without any content).

    I am working with the latest gutenberg version.

    Can you help me?

    Best
    Lukas

    1. Antonio Villegas Avatar

      Hi Lukas. I’ve made some changes in the source code on GitHub. Take a look at it because that probably fixes your issues.

  4. Lukas Avatar

    Hello
    Thank you for your recent fix, it is working now like a charm.
    What I was searching in the meantime was a solution that custom image sizes are loaded, not always the full size image. I already talked to some experts but they were not able to say if there is any solution for plugins, like the stadard image block are using. Would this be possible to make? Do you know more about this?

    1. Antonio Villegas Avatar

      Hi Lukas. I’m not sure how to get the proper image size. Looking at the project in GitHub it seems that there is still work to do on this direction. Honestly, more documentation about it is necessary. I think we should wait until then or go to Slack and ask the Gutenberg developers directly.

  5. GregH Avatar
    GregH

    After some time of struggle, I found that blocks.RichText now needs to be changed now to wp.editor.RichText (due to recent changes in the API, I guess). You can pass “wp.editor” to the function as “editor,” then use editor.RichText to match what is done with the “blocks” variable.

  6. Dani Pastore Avatar
    Dani Pastore

    Thanks for this tutorial Antonio!

    Any chance for you to give some hints of how to transform this in a slider using repeater field concept?

    1. Antonio Villegas Avatar

      Thanks for the comment, Dani. You could add some settings for the block in the block sidebar to allow adding more fields. The slider behavior should be performed in frontend (CSS+JS, not affecting the block HTML stored during save() method).

  7. Dani Pastore Avatar
    Dani Pastore

    Thanks! I’ll try to go for that 🙂

  8. Chris Avatar
    Chris

    I found wp.blocks.MediaUpload needs now also to be wp.blockEditor.MediaUpload

    more info: https://developer.wordpress.org/block-editor/developers/backward-compatibility/deprecations/

    1. David Aguilera Avatar

      Indeed. Thanks, Chris!

  9. Daniele Avatar
    Daniele

    Hi,
    this tutorial is very useful thanks!

    Could I ask you a little help in understanding the way I should create a Gutenberg block wich applies the art-direction rules and resolution switching rules to the images of the word press site, hence the block should select the images in the site.

    Thanks if you could help me
    best wishes
    Daniele

    1. Antonio Villegas Avatar

      Do you mean using the proper image thumbnail size depending on the device screen size? I’d recommend taking a look at the core/image block here. There must be something there that can help you.

Leave a Reply

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

I have read and agree to the Nelio Software Privacy Policy

Your personal data will be located on SiteGround and will be treated by Nelio Software with the sole purpose of publishing this comment here. The legitimation is carried out through your express consent. Contact us to access, rectify, limit, or delete your data.