How to extend blocks in the Gutenberg editor on WordPress
With the introduction of WordPress 5, we now have a new powerful tool at our disposal: Blocks. Blocks let us build custom experiences in the WordPress editor, making it easier for content managers to write and maintain content on the website.
Example: How to use block filters to add “Open in a new tab” to core buttons
Let me first show you the full source code – and then break it down below:
We use this filter to look for a
core/button block and use the spread operator to add an attribute “target”:
We then use this filter to add a new panel with a
ToggleControl control to work with the attribute “target” defined above. So you have a nice little toggle control in the editor to turn it off or on. If it’s on, we set the value “_blank” to the attribute, if not, we set an empty value.
Notice we also set the value
noreferrer noopener to the “rel” attribute. We do this to avoid an error in the editor, which specifically looks for this value for all links which have a target value set to “_blank”.
Caveat: Although the whole point of this filter is to modify the element, you… can’t modify it… directly? Which is why we use the
cloneElement function, which essentially allows you to clone the original object and modify it instead.
I appreciate that this is a lot to take in if you’re just starting off, so I’d recommend doing a bit more reading in order to fully get a grasp of this. You can also use this same method to extend not only any core block, but any block at all!
Happy coding! 🙂