Discover with this tutorial how to display a custom field in the WordPress block editor, without plugins or custom blocks.
One of the new features of WordPress 6.5 is that it incorporates a new API called Block Binding. This provides the option to display custom fields directly in a block. This is fantastic news as now you don’t need to create a custom block but can use an existing one.
Currently there are only 4 blocks that allow you to do this:
- Paragraph
- Heading
- Button
- Image
This already allows you to do some very interesting things and I’m sure that in future WordPress updates this feature will be extended to more blocks.
At the moment, the source of the custom fields are the post metadata, but in the next tutorial I will explain how to extend the sources.
This new option opens up a wide range of opportunities.
In this tutorial you will learn how you can enter the reading time in a paragraph block so that you can display it wherever you want.
Steps to display a custom field using Block Binding
1. Register the metadata
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
With this code you use the register_meta()
function to register the reading_time
metadata.
2. Enter the block where you want
Once you have registered the new metadata, it will appear in the dropdown of the metabox at the end of the entries:
3. Insert the block where you want
WordPress 6.5 doesn’t have a visual interface to manage block binding, so you have to do it from the code editor.
To access it go to the 3 dots in the top right corner of the editor and select “Code Editor”:
Pro tip: use the keyboard shortcut: Cmd + Alt + Shift + M
to go faster. 😉
Once there, add this HTML:
<!-- wp:paragraph {
"metadata":{
"bindings":{
"content":{
"source":"core/post-meta",
"args":{
"key":"reading_time"
}
}
}
}
} -->
<p></p>
<!-- /wp:paragraph -->
In this case, you use a paragraph block to get the reading_time
metadata via the Block Binding API.
Once you enter it you can go back to visual editing the content. You will see something like this:
But on the front side the metadata value will be displayed.
The advantage of having a custom field in a block is that you can layout it to your liking.
For example, you can display it before the page content either manually or within a page template.
Conclusions
You can see how easy it is to display the custom field you want anywhere on the web thanks to the Block Binding and being able to display it directly in a paragraph block.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉