Last night, I was looking at my phone a lot later than I should have been. I should have been stretching, but instead I was on twitter, saw this tweet, asking if there is a way to show a custom field in WordPress’ block editor:
Before I shut my phone off, I replied:
🌲Generate a new plugin using @PluginMachine with 1 block and 1 editor sidebar.— Josh Pollock | Josh412.eth (@Josh412) April 7, 2022
🌲Copy the logic for getting and setting meta value in editor from sidebar.
🌲Delete sidebar and paste copied code into the block.
🌲Add PHP render callback, that return latest value of field.
And yes, you can do that with ACF, but I figured I could build a plugin to do this in less than an hour and since I was up early today, I figured I’d try to build it this morning, while having my second cup of tea.
Here is part one of the video where I created a block that lets you set which meta field you want to display. I also added the ability to set the fields value. That needs a little more work.
In part two of the video, I solved those problems, using two WordPress hooks:
You can take a look at the pull request I made while working on part 2 or watch the video:
What This Plugin Does
- Adds new block called “metablock” to block editor
- Block lets you select the name of the meta field to show.
- It also lets you save the field’s value.
- This is not working yet. I will fix the issue in the second part of the video.
- It uses a server-side render callback to get the current value of the meta field.
- Creating Dynamic Blocks
- Creating Block Types Plugins With Plugin Machine
- A tutorial on the useSelect and useDispatch hooks
- Documentation for WordPress data module.
- Documentation for register_block_type_from_metadata function
Get The Plugin Or Make Your Own
If you want to download or fork the plugin, please use these links:
- Github repo: https://github.com/imaginarymachines/metablock
- Latest ZIP file: https://github.com/imaginarymachines/metablock/blob/main/joshmetablock.zip
If you want to build your own, sign up for a 14 day free trial of Plugin Machine to get started.