How to Create Your First Block For Gutenberg

WordPress

If only I had a calendar where I could schedule all my upcoming posts… Hold on a sec, I do have one! And it even helps me to promote it on social networks! Discover our new plugin!

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.

PoorMehGoodVery GoodAwesome! (3 votes, average: 4.67 out of 5)
Loading...

by

Antonio obtained his PhD in Computer Science at UPC. He has several publications in the field of data mining and information retrieval applied to conceptual modeling and health informatics. He specialized in the design, development, and integration of web services and cloud applications. He's an active contributor to the WordPress community and participates in meetups, seminars and WordCamps.

5 thoughts on “How to Create Your First Block For Gutenberg

  1. 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. 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. 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. 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.

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.