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.
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:
- 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 useattr()
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 iediv class="wp-block-gutenbergerli-faq" data-id="[value]"
(I can’t use brackets here, everything disappears.)
- In
edit
I wanted to see the id to reassure myself it was there and not changing so used theInspectorControls
andBlockDescription
components to add this information in the sidebar under the block tab which I assume is called the inspector? The variablefocusedEditable
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.
- 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
)
- 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.
Leave a Reply