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?
There it is, something I can use to tell that block apart from all the others.
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:
- To use the InspectorControls and BlockDescription components, we have to define them. And because I wanted to pick up the
data-idattribute 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.)
- 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.)
editI wanted to see the id to reassure myself it was there and not changing so used the
BlockDescriptioncomponents to add this information in the sidebar under the block tab which I assume is called the inspector? The variable
focusedEditableis 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.
- 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
- In save, I need to set attributes.id which should now be there thanks to step 4
- And finally, add it to the front end
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.