Gutenberg identifiable but still non-global blocks


I wanted to be able to add meta data to individual blocks, so needed a way of telling the blocks apart. What I’ve ended up doing is straightforward: each block gets a data-id attribute which contains the block’s uuid at time of creation.

What does this look like on the front end?

Screen Shot 2017-09-01 at 13.35.47

There it is, something I can use to tell that block apart from all the others.

I added it to the Gutenbergerli/faq blocks; here is the commit which shows what I added.  (You can read about the initial Gutenbergerli/faq block here.)

NOTE: I’ve just realised that if I try to edit a post with Gutenberg after it’s published, the editor whitescreens. This seems to be an issue with Editable and is outlined here. Might be user error but I’m sure they’ll tell me in a nice way. Here’s what I’ve done to mitigate / fix. (edit a bit later: And here’s the real fix. See the linked commits in gutenberg-examples for explanations.)

A walkthrough of what I did to create and add the data-id attribute:

  1. To use the InspectorControls and BlockDescription components, we have to define them. And because I wanted to pick up the data-id attribute to use as my block id, I needed to say that I wanted to use attr() so it knows to load it. (I am unclear of the correct words to use here, I’m hoping you get the drift.) Screen Shot 2017-09-01 at 11.29.44

  2. Add id to my list of attributes and tell it where to find the value. This uses attr() to pick it up ie div class="wp-block-gutenbergerli-faq" data-id="[value]" (I can’t use brackets here, everything disappears.)

    Screen Shot 2017-09-01 at 13.17.21.png


  3. In edit I wanted to see the id to reassure myself it was there and not changing so used the InspectorControls and BlockDescription components to add this information in the sidebar under the block tab which I assume is called the inspector? The variable focusedEditable is what keeps track of which block has the focus. And note that I wrapped this and the other bit in a div. From the blocks in Gutenberg itself, it looks like I can return an array but I’ve kept it to one node. Screen Shot 2017-09-01 at 13.20.47

  4. I need to set the attribute if it’s not set already (ie when a block is created) and put it in the div. (This is still in edit) Screen Shot 2017-09-01 at 13.26.26.png

  5. In save, I need to set attributes.id which should now be there thanks to step 4 Screen Shot 2017-09-01 at 13.28.36

  6. And finally, add it to the front end Screen Shot 2017-09-01 at 13.30.26

And that’s it! Now I have something to call my block, even if it’s an unpronounceable name that I don’t think I’d name a child.

Leave a Reply

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

By submitting this comment, you are agreeing to the use of Akismet which helps reduce spam. You can view Akismet’s privacy policy here. Your email, website and name are also stored on this site.