Building a Gutenberg Block

After completing Zac Gordon’s wonderful Gutenberg Development Course, I wanted to try building my own block. It was more difficult than I expected, but a great learning experience. For comparison, see my article on building custom blocks with Advanced Custom Fields.

I added a “List Subpages” block to my BE Subpages Widget plugin (code here). This lets you select a page and dynamically lists all its subpages.

The biggest hurdle is my lack of knowledge of modern JavaScript development. I’m a theme and plugin developer, so I’m comfortable with PHP and frontend markup. I use a bit of jQuery in theme development, but nothing special.

There was a lot of copy/pasting pieces from existing blocks while I tried to figure out the proper syntax to implement what I want. I’m sure this code could be written better if I knew what I was doing.

Getting Started

I followed the example code from the Gutenberg Development Course to setup the plugin initially. You could also use the create-guten-block tool or the wp cli command wp scaffold block.

In terminal, run npm install in the plugin’s directory. Then run npm run dev, which will monitor the files for changes and recompile the resulting CSS/JS into the assets directory.

In the main plugin file I’m enqueuing the editor-specific Javascript using the enqueue_block_editor_assets hook. If my block required its own styling or JS, I’d also enqueue block-specific CSS and JS using enqueue_block_assets hook, which applies to both the editor and frontend, ensuring the block looks the same in both places.

Starting the block

In the block’s index.js file, use registerBlockType() to create a block (example). You specify a unique name, some basic parameters, and two functions: edit and save.

The edit function is what’s rendered in the Gutenberg editor. When the block is in focus, I’m displaying a dropdown menu, and when the block is out of focus I’m displaying the actual subpages list.

The save function is saved into the post content and is shown on the frontend. Since my block is outputting dynamic content, my save function is empty and I created a PHP callback function to handle the output, similar to a shortcode.

This is one complaint I have about Gutenberg.  All dynamic elements need to be implemented twice: once in JS for the edit() function so it’s visible in editor, and again in PHP for frontend render. You’ll need to be careful to keep your WP_Query returning the same results as your JavaScript REST API Query.

Gutenberg is readable and reusable

Gutenberg’s code is very clean and logical. Everything is broken down into small, single-purpose files. Reusable components are accessible from global variables.

In my plugin I wanted a dropdown menu with a hierarchical page listing.  I found an existing area of Gutenberg that already did this – the “page parent” dropdown in the Page Attributes section.

In the parent.js file in /packages/editor/src/components/page-attributes, they’re using <TreeSelect> to create this hierarchical select menu (see here). At the top of the file you’ll see they are importing that component from another file:

import { TreeSelect } from '@wordpress/components';

You can’t copy this line directly, but you can use something similar:

const { TreeSelect } = wp.components;

I used this approach to find all the pieces I needed and import them all. I also kept my code simple and readable by breaking my functionality into separate files.

Querying Posts

You can use withAPIData() to query for data using the REST API. The examples I found in Gutenberg used a constant like applyWithAPIData to build the query, then applies it to your component on export. You can then access the JSON result of that query by using whatever variable you returned in the constant (in this case, pages).

See the REST API Handbook for more information on querying.

Lots to learn

It truly is time to “Learn Javascript Deeply” to keep up with future WordPress development. To that end, I’m:

  • Reading Eloquent Javascript
  • Taking Wes Bos’ courses Javascript30 (free), ES6 for Everyone, and React for Beginners.
  • Keeping up with Gutenberg development. I’m reading all the issues and pull requests to follow what’s changing and improve my understanding of the underlying code.
  • Contribute where I can. Here’s my first bug report and patch.
  • While building client sites, find elements to build as Gutenberg blocks in my free time. Implementing these real-world examples will help prepare me for when I’m actually building client sites with Gutenberg.

We’re still many months away from Gutenberg merging into core. But if you’re like me, it’s going to take that long to become technically competent in modern JavaScript and comfortable building websites using Gutenberg.

Now is the perfect time to start learning.

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Comments

  1. Hi bill thanks for your article.
    I just have one question
    I wonder how stringify works with array. I mean when I have

    const query = stringify( {
    context: ‘edit’,
    per_page: 100,
    orderby: ‘menu_order’,
    order: ‘asc’,
    _fields: [ ‘id’, ‘parent’, ‘title’ ],
    } );

    I get context=edit&per_page=100&orderby=menu_order&order=asc but then how do it work with _fields: [ ‘id’, ‘parent’, ‘title’ ] ?

    • I console.log‘d the resulting string and it is: “/wp/v2/pages?per_page=100&parent=80&orderby=menu_order&order=asc&_fields=id%2Cparent%2Ctitle”

      It looks like the array items are simply separated with commas (%2C = comma).

  2. Thank you for this interesting tutorial.

    Question: How do you get the rest of the sub pages if there are more than 100?

  3. Thank you. There is a parameter ‘page’ as well, maybe the request can be called more times after each other but I dont know how to put this in the get() function and how to find how many pages.

    There must be a way, so many use cases for blocks have more than 100 results and writing own endpoint for every block sounds overkill.

    • You could just run two API queries, and on the second one add &offset=100. That will get you posts 101 – 200.

      As I mentioned in the post, I’m not very experienced with JavaScript so I’m not sure the best way to write that. You could probably duplicate the whole `applyWithAPIData` constant (ex: `applyWithAPIData2`), return a different property (ex: `pages_2`), then in the render function combine the two arrays. But I’m sure there’s a better way.

  4. Hey Bill, I’ve completed the same course from Zac Gordon and very exciting to work on Gutenberg for my plugins and themes. Thanks a lot for sharing your experience. It’s really inspiring.

  5. Hi Bill
    Thanks for your article.
    I have one question about: const pageItems = get( pages, ‘data’, [] );
    What are you trying to do here? What is ‘data’ and the empty array

    • At the bottom, applyWithAPIData builds the WP REST API query and returns it as pages (see here).

      We then pass that API query url to SelectSubpages here.

      So inside SelectSubpages, when I call get( pages ), I’m doing the actual API query using the “pages” query URL generated by applyWithAPIData.

      As for the ‘data’ and empty array part, I don’t recall exactly. I think I copied the general structure from an existing block in Gutenberg and it probably had that (example). I’m guessing the second parameter says what we want (give us the data), and the third parameter is a default value to use if it’s empty or an error.

  6. I have just spent the morning catching up with Gutenberg, initially just to check compatibility with a custom plugin I’m building for a site.

    I have to admit I’m struggling, I thought things would get easier, but I’m glad you also found it more difficult than expected. I thought it would be a simple process to just replace a metabox on a CPT with a block of structured data (name, address, phone, email) and then use that data in the same way as post_meta.

    For the moment, I’m dropping back and reverting to traditional meta to get the job done, a sits going to take a while for this to sink in. It is a significant change of approach. I guess many devs are in the same boat.

    • I agree, it’s a lot more difficult than I had expected, especially since everything is JavaScript based.

      On a recent interview with Matt Mullenweg about Gutenberg, Matt was asked if (a) he thought creating a block was difficult, and (b) if there would be a PHP-only approach for block creation in the future. He answered “No, it isn’t hard to make a block” and just left it there.

      I believe ACF will provide a way to create block-based metaboxes, and maybe through that process they’ll create a whole “block builder” so you don’t actually need to hand code blocks yourself.

      For now, I’m adding Gutenberg support in my themes for simple pages that just use the main content editor. I’m still using metaboxes for complex pages. If a need arises where I build a shortcode, I’ll probably also build a Gutenblock for that as well.

      It will probably be 6-12 months before I can consider building everything in the Gutenberg editor. Gutenberg itself needs to mature, and then the WordPress developer community needs to define best practices for building new blocks.

    • I’m also experiencing the same steep learning curve as I dive into Gutenberg today. It has been a great relief to find this blog post and comments from people with with a similar experiences. I was starting to wonder if I’m just not that smart!

  7. So do you think this will replace the concept of the ACF Flex Content field? I learned about this from you and have an entire Genesis page builder theme based around the concept. Will you be replacing your Flex Content setup with Gutenberg blocks?

    • At some point in time, yes. As mentioned in the above comment, I think ACF or someone similar will simplify how to build a block. But for the foreseeable future, I’ll be using post-meta based flexible content pages (I call them disabling the editor on those specific templates.

  8. Hey Bill, great post!

    I found your post and code pretty enlightening – especially not yet having dug in too much to Gutenberg. I have to say that while I applaud the Gutenberg team for already having a handbook in progress, it leaves a lot to be desired for what I would consider to be the dominant WordPress develop demographic: strong basis in PHP and just learning modern JS via React/ES6 etc.

    There’s kind of an assumption and tone in the handbook that you are already familiar with React/Gutenberg terminology. To really be an effective resource, I think they’re going to have to do a better job of breaking it down.

    In terms of some of the limitations you highlighted, I too am a little concerned about how Gutenberg is reshaping the “WordPress way”. In theory it might seem like a good idea to require creating the equivalent of a render preview in JSX, but in practice I find it to be shortsighted and annoying. I hope they come up with a more efficient, intuitive way to address that problem.

    One would think that it should be possible to simply defer to the PHP-defined rendering callback instead of having to reinvent the PHP wheel in JSX for the benefit of rendering the edit preview. Good stuff, thanks for the post 🙂

    • Thank you for the kind comment!

      I agree, at a minimum you should be able to register a PHP callback for the preview. If core doesn’t add it, I bet someone will build it and plugin developers will bundle it.

  9. Awesome post, I feel I am in a very similar position to yourself. I have built a couple of plugins, many WordPress sites, but my knowledge of modern Javascript is limited and I rely heavily on jQuery.

    I have just started a recent blog post series about learning React, but I think I’ll checkout some of your links and look into Modern Javascript as well, thanks for the resources!

  10. Hi Bill,

    Good choice on the Gutenberg course! its a nice overview w/ some good example blocks to reference.

    I saw your educational task list at the end of this article. Since I’m learning from the 4 resources you mentioned I thought I’d contribute one:

    I followed the React track at Treehouse early last year. For the cost it was a good 5 hour introduction with plenty of JSX practice.

    https://teamtreehouse.com/tracks/learn-react

  11. withAPIData HOC not displaying data in editor after post edit page reload if window width > 782px. How can i solve this issue?

  12. After using several “builders” and theme bundles, such as WPBakeryBuilder, Elementor, Beaver Builder, SiteOrigin,PageBuilder and others, I still feel Divi is the easiest and best as far as themes and builders are concerned. Some of these builders require going back and forth from frontend to backend, and some just don’t have all the features.

    Personally, I think there will be many updates coming for the new WordPress format, and those companies who have created great themes and builders, like Divi, will make WordPress think twice about changing the system. Maybe WordPress should consider keeping the current format of WordPress and introduce the new platform separately? I just don’t see WordPress catching up to Divi or some of the other builders to make it “standard”. Especially if WordPress still has outdated plugins and themes in their repository. I am not thrilled about the change in WordPress’ format.

Leave A Reply