You’re undoubtedly acquainted with creating custom post meta using add_meta_box() if you’ve dealt with WordPress before Gutenberg. When updating a post, you may use this feature to add a meta box with your own content to the bottom or side. This strategy works in the Gutenberg editor as well.

How to add the Custom Field to the Sidebar

Keep in mind that the code is written in ES6 syntax. This indicates I’ve built up a webpack configuration to compile my file into a browser-friendly JavaScript file. Visit this link to learn how.

The steps

  • Registering the post meta keys using register_post_meta()
  • Creating a file that will be included to the editor only
  • The file will include the component that will add the custom field to the sidebar using registerPlugin()
  • Display anything we want in the component

Let’s register the post meta

Don’t forget to set the ‘show_in_rest’ field to ‘true’. This will enable us to use the custom field in the editor and will make it available to the WP REST API.

Registering the plugin

I’m assuming you understand how to enqueue scripts and can replace the values with your own. I specify the path to the build file as the second parameter. I added ‘wp-edit-post’ as a dependency to guarantee that our script isn’t loaded too soon. This is the package we’ll use to deal with post meta.

Create two files:

  • index.js
  • meta-fields.js

Let’s explain

We have access to the powerful select() function inside withSelect(). We can get the meta values for the current post using select(). We can limit post meta to a single post type. If we get the post type of the current post, we can make sure that our component only renders our code if we’re on the right post type.

We can define functions to run in our component with withDispatch(). We create a function that will update the post meta using dispatch().

If successful, you should be able to see the custom fields in the sidebar on the edit post page.

How to add Post Meta Fields to Gutenberg Sidebar on Edit Post