The new WordPress editor (codenamed Gutenberg) is due for release in version 5.0. Now is the perfect time to get to grips with it before it lands in WordPress core. In this series, I'll show you how to work with the Block API and create your very own content blocks which you can use to build out your posts and pages.

In the first post of this series, we had an overview of the Block API and created a simple block for testing. We'll be taking a closer look at the Block API shortly, but first let's edit the default block we created in the previous post to get a feel for how easy it is to make changes to an existing block.

If you remember, our custom block rendered differently on the front and back end to demonstrate that you have complete control over how the block is rendered inside the editor and how site visitors see the block.

If you've been following along then open up the /wp-content/plugins/my-custom-block/src/block folder where the block source code is located. That folder contains a JavaScript file and two Sass files, which control the block's behavior and how it renders inside the editor and on the front end.

The block.js JavaScript file contains JSX, which is transpiled during the build process into valid JavaScript. Similarly, the two Sass files are converted to standard CSS.

During the build process, these files require processing to create the distribution files inside the plugin's dist/ folder. These are the actual files enqueued by WordPress as they contain valid JavaScript and CSS that all browsers can understand.



Fortunately, the create-guten-block toolkit handles building and transpiling for us by watching for changes to our block files. This is a really nice feature as it's one less thing for us to worry about. We can just focus on writing our block code (and styles), and the plugin files will all update automatically. Nice!



Just make sure you run the npm start command from inside the plugin root folder to trigger file watching.

Time to Edit Some Code!

Don't worry about the details of the JSX code in block.js just yet as we'll cover that in detail later on. For now, let's just focus on making some simple changes to the block output for the front and back end views.

Open up block.js, find the edit method for the object that's the second argument passed to registerBlockType() , and replace it with the following:

This method controls how the block renders in the editor window. Now find the save method and replace it with:

This method is used to render the block output on the front end.

In style.scss, replace all styles with:

Then, in editor.scss, replace all styles with:

You can see in the screenshots below how these changes affect the rendering of our block depending on whether we're viewing it in the editor window or the front end.

We won't cover enqueueing block scripts just yet, but it's enough for now to know that editor.scss styles are only applied to the editor window and style.scss is added to both the editor window and the front end. Therefore, styles that are used both in the editor and front end can be omitted from style.scss.

Notice how in the Sass files we reference a lengthy CSS selector to target our block elements.

This class is automatically added by Gutenberg to the block container element on the front end, but we have to apply it manually in the editor window to get the same class, as you can see in the edit method below.

The class name generated by Gutenberg is determined as follows: wp-block-[block namespace]-[block name .

In our case, we used the create-guten-block toolkit to create our block, which uses cgb for the namespace by default, and block-my-custom-block is based on the block name we specified. This results in the CSS class name wp-block-cgb-block-my-custom-block being added to the block container. The namespace and block name are used by Gutenberg internally to uniquely identify blocks.



When making changes to block files there, I found a couple of pain points worth mentioning.



Firstly, when making changes to the edit method, I found myself having to clear the browser cache before refreshing the editor window in order to see the latest changes. This didn't happen all of the time, but it was quite often the case. If you find the same thing happening to you, just clear your browser cache and try again.



Secondly, when editing the contents of the save method, something strange seems to happen to the editor window when it's next refreshed.

To demonstrate this, I added a new list item ( <li>Indigo</li> ) in the save method and then refreshed the post editor (after having to clear the cache again, of course!). Here's the result:







If you choose either Convert to Blocks or Edit as HTML then you get presented with the contents of the save method, which is meant to be viewed on the front end and not in the editor.







This is very confusing, and the only obvious way to bring things back to normality was to delete the block from the editor window and reinsert it again. As I mentioned in the previous post, Gutenberg is still a work in progress, and this is a good example of that!

Hopefully this will be made more intuitive in future versions, but for now it's just something to watch out for. When making changes to the save function, be prepared to delete the related blocks in the editor window and add them again.

As mentioned previously, the output from the save and edit methods can be completely different. However, in most cases you'll probably want the front end output to match the editor output so that the editing experience is as consistent as possible with front-end rendering.



In our contrived example above, I only added different content and styles in the editor and front-end view for demonstration purposes.



Block API Overview



The Block API is made up of a set of JavaScript objects added to the global wp admin object. And because wp is global, we don't need to specifically import it in our source code—it's available on demand.



The objects available in wp depend on the admin page you're currently viewing. For instance, if you're customizing your site then wp includes the main customizer API object.

Currently, however, the Gutenberg Block API is only available on the post editor. I anticipate this will change in the future when integration between the post editor and site customizer moves closer.



You can view the structure of wp by opening up the Gutenberg editor and entering wp in the browser console.

As you can see, wp contains many objects, but the ones we're most interested in are:

These objects give you access to all the tools needed to create some very complex blocks. Try typing their full object names in the browser console to explore these objects further.



For example, if you type in wp.blocks and expand the object, you'll see one of the available functions is registerBlockType() . This is a very important function which we'll cover in depth in the next post



The wp.elements Object



This object is the abstraction layer on top of React (and ReactDom) which exposes React functionality in a predictable and consistent manner. This remains true even if the underlying implementation is altered or changed completely.

So long as the interface stays the same, plugins that interact with the Block API won't be affected in the future.



The wp.blocks Object



The core function to create a block ( registerBlockType() ) is contained in wp.blocks along with other functions necessary for general block management such as:



getBlockType()

getBlockContent()

getBlockAttributes()

hasBlockSupport()

isValidBlock()

This object also contains a set of reusable blocks that you can include in your own blocks to provide functionality with no additional overheads. These out-of-the-box ready blocks can speed up block development dramatically, and we'll be making use of some of them in the next post as we delve further into block creation.



Some of the available ones are:



alignment toolbar

autocomplete

media uploader

color palette

rich text editor

The wp.components Object



The wp.components object also contains reusable components, but these are more generic and are typically used to create additional UI elements in the editor window, such as control panels for block settings.



These include:



button

checkbox

code editor

dash Icon

date/time

dropdown

menu item

radio button

range control

The wp.data Object



The data module manages application state in the Gutenberg editor, which includes storing settings for each block. We'll be taking a look at different ways you can add settings to a block in the final post of this series.

wp.data is implemented on top of Redux, so when Gutenberg is merged with core, we won't just have access to React but also to a complete centralized data store powered by Redux!

The wp.i18n Object

Plugins and themes have been able to easily translate PHP strings for years now, and a similar method is also available for translating strings in JavaScript thanks to the wp.i18n object. This means all strings contained in your block—including the block name, keywords, and labels—can be translated into any language.



If you've used the standard PHP translation functions before then you'll feel right at home as the process is pretty much the same. I think this is a smart move as it will encourage developers to enable string translations in their blocks from the outset.



Inside your block code, translating a string is as simple as:

Conclusion



In this tutorial, we've implemented a basic block and edited the code. We've also seen that we have total control over block rendering and can have different block views in the editor compared to the front end.



The editor still has some issues which can take you by surprise from time to time—this serves as a reminder that Gutenberg is still in development and may not be ready for use on production sites.

Finally, we finished off with an overview of the block API, which introduces several new objects on the global wp JavaScript object to create and manage blocks.

