How to create Meta Boxes and custom fields to post in Gutenberg

Jan 20, 2023
Metadata refers to information that is stored in the database. When it comes to WordPress metadata, this is the data associated with posts, users as well as terms, comments , and posts.
With the numerous-to-one connection to metadata within WordPress The options you have are pretty limitless. You have access to the variety of meta choices you desire and store just about anything inside it.
--Facebook

Here are a few examples of the metadata you could attach to your post by creating custom fields

  • Coordinates that correspond to a geo-physical property or for a location
  • The day that an event takes place
  • The ISBNor Author of a book
  • The mood of the day for the author of the article

There are many other.

From the start, WordPress does not provide the ability to easily create and manage custom fields. The Classic Editor and the custom fields will appear in an area at the right side of the page. It is located just beneath the editor for posts.

Custom fields in the Classic Editor
Custom fields within Classic Editor. Classic Editor.

In Gutenberg, custom fields are turned off by default, however, you are able to display them by clicking on the relevant item in the settings for your article.

Adding the custom fields panel to the block editor
The custom fields panel can be added in the block editor.

There isn't a solution to display the metadata that you wish to display on the frontend of the website without using the plugin or getting involvement with the code.

If you're already a WordPress user, there are many great plugins to help customers available. If you're a programer and want to make the most benefit from WordPress Custom Fields, integrate these fields in your block editor, and display these fields in the frontend of your WordPress website creating a custom Gutenberg block. If yes, you're in appropriate spot.

Do not be worried. While creating a plugin that can control custom fields on two editors can be a bit challenging We'll simplify the process as we can. After you've understood the ideas we'll discuss in this article and you'll acquire the knowledge needed to manage custom meta fields in Gutenberg and build all types of sites.

So, here is our rundown:

Make a Block Plugin the creator-block tool, which is an official creation tool

First, build an entirely new plugin that includes all dependencies and the files needed to build an entirely new kind of block. The block plugin allows the user to build an easily custom block type that can be used for creating and managing custom metadata.

npx @wordpress/create-block

When asked, include the following details:

  • The template version to be used in this block is: dynamic
  • Block slug used to identify (also the name for the folder that is used to output): metadata-block
  • The internal namespace that is used to name the block (something distinctive for your product): meta-fields
  • The display title for your blockis: Meta Fields
  • A brief description of the block (optional): Block description
  • The dashicon which helps to distinguish this block (optional): book
  • The name of the category allows users to find and navigate blocks widgets
  • Do you wish to modify your WordPress plugin? Yes/No

Take the time to go through those information and see how they're utilized.

  • Block slug that is used to identification specifies the plugin's folder name and textdomain
  • The namespace utilized internally for the block's name specifies the block's namespace as well as the internal namespace as well as the function name prefix used in the entire source code for the plugin.
  • The title of the display for your block is your name of the plugin and also the block's name that is used by editors interface.

This process can take a couple of minutes. After the procedure is finished it will give you a list of available commands.

Block plugin successfully installed
Block plugin is successfully installed.
CD metadata block NPM

Now you are ready to make your own code. The next step is alter the core PHP script used by the plugin so that you can make Meta boxes to use with The Classic Editor.

Prior to moving on to the next stage, install and enable before proceeding to the next step, install and activate Classic Editor plugin.

Once you have done that, visit the plugins section and turn on the latest meta Fields plugin.

Activate plugins
Activate plugins.

Include Meta Box Meta Box to the Classic Editor

The WordPress API offers beneficial functions for creating custom meta boxes that include the entire set of HTML elements that your plugin requires to work.

To get started, append this code in the PHP file for the brand new plugin that you've made:

// register meta box function meta_fields_add_meta_box() add_meta_box( 'meta_fields_meta_box', __( 'Book details' ), 'meta_fields_build_meta_box_callback', 'post', 'side', 'default' ); // build meta box function meta_fields_build_meta_box_callback( $post ) wp_nonce_field( 'meta_fields_save_meta_box_data', 'meta_fields_meta_box_nonce' ); $title = get_post_meta( $post->ID, '_meta_fields_book_title', true ); $author = get_post_meta( $post->ID, '_meta_fields_book_author', true ); ?> Title Author 

The function that adds a meta box. function that is used to register a the meta box as a new one. Furthermore, the callback function creates the HTML to be injected into the metabox. It's not our intention to go into more detail on this subject since it's beyond the scope of our piece however, we'll give all the relevant information in the following places: here, here as well as here.

// save metadata function meta_fields_save_meta_box_data( $post_id ) if ( ! isset( $_POST['meta_fields_meta_box_nonce'] ) ) return; if ( ! wp_verify_nonce( $_POST['meta_fields_meta_box_nonce'], 'meta_fields_save_meta_box_data' ) ) return; if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( ! current_user_can( edit_post' and the post's ID ) ) return If ( ! isset( $_POST['meta_fields_book_title'] ) ) return; if ( ! isset( $_POST['meta_fields_book_author'] ) ) return; $title = sanitize_text_field( $_POST['meta_fields_book_title'] ); $author = sanitize_text_field( $_POST['meta_fields_book_author'] ); update_post_meta( $post_id, '_meta_fields_book_title', $title ); update_post_meta( $post_id, '_meta_fields_book_author', $author ); add_action( 'save_post', 'meta_fields_save_meta_box_data' );

Make sure you check the documentation online for more details. It will highlight only the underscore ( _) preceding that meta-key. This will tell WordPress to block the keys for custom fields in the custom fields as default. This also makes your customized fields visible only in the meta box you have created for your custom field.

Below is an image which will show how the custom meta box is similar to Classic Editor. Classic Editor.

A custom Meta Box in the Classic Editor
Custom Meta Boxes in the Classic Editor.

So, before moving on, we'll tell WordPress to remove the custom meta box from the block editor by adding the __back_compat_meta_box flag to the add_meta_box function (see also Meta Box Compatibility Flags and Backward Compatibility).

Now let's go back to the function that creates the meta box. We will modify it in the following way:

// register meta box function meta_fields_add_meta_box() add_meta_box( 'meta_fields_meta_box', __( 'Book details' ), 'meta_fields_build_meta_box_callback', 'post', 'side', 'default', // hide the meta box in Gutenberg array('__back_compat_meta_box' => true) ); 

Save the plugin file and go back to the WordPress administrator. It shouldn't view your custom meta box within the block editor any longer. If you activate your Classic Editor, instead, your meta box with customisation should show up within the Classic Editor.

Customize Meta Fields in the Gutenberg Block Editor (Three Choices)

In this article , we'll go it an extra step and look at how to add meta-specific fields to a blog post.

There are several ways to store and use post metadata within Gutenberg. We'll go over the following:

Create an Custom Block store and display the custom Meta Fields

In this article we'll explain how to make and manage custom meta fields within the framework of a dynamic block. According to the Block Editor Handbook, a post meta field "is a WordPress object which is used to hold the information associated with the post" and it is necessary to register a brand new meta field prior to being able to utilize it.

Register Your Own Meta Fields

Return to the file to look for the plugins. Incorporate the following code

/** * Register the custom meta fields */ function meta_fields_register_meta() $metafields = [ '_meta_fields_book_title', '_meta_fields_book_author' ]; foreach( $metafields as $metafield ) // Pass an empty string to register the meta key across all existing post types. register_post_meta( '', $metafield, array( 'show_in_rest' => true, 'type' => 'string', 'single' => true, 'sanitize_callback' => 'sanitize_text_field', 'auth_callback' => function() return current_user_can( 'edit_posts' ); )); add_action( 'init', 'meta_fields_register_meta' );

register_post_meta is a meta-key which is unique to the post type. With the below code has registered two meta fields that are custom-made for all post types which are registered on your site that provide the creation of custom fields. For more information, go to the function reference.

When you are done, then open the file. Then, start it up again. Finally, open the src/index.js file of the block plug-in you're using.

Create the Block Type and add it to the client

Now navigate to the wp-content/plugins/metadata-block/src folder and open the index.js file:

import registerBlockType from '@wordpress/blocks';import './style.scss andimport Edit from './edit'; import metadata from './block.json';registerBlockType( metadata.name Edit: );

Build the Block Sort

Navigate to the wp-content/plugins/metadata-block/src folder and open the edit.js file. The following codes (comments deleted):

import __ from '@wordpress/i18n'; import useBlockProps from '@wordpress/block-editor'; import './editor.scss'; export default function Edit() return ( __( 'Meta Fields - hello from the editor! ', 'metadata-block' ) );

This is where you'll insert your code which generates the block to be rendered in the editor.

First thing you need to do is import all the elements and functions required to build the block. Here is the complete listing of all the dependent components:

import __ from '@wordpress/i18n'; import useBlockProps, InspectorControls, RichText from '@wordpress/block-editor'; import useSelect from '@wordpress/data'; import useEntityProp from '@wordpress/core-data'; import TextControl, PanelBody, PanelRow from '@wordpress/components'; import './editor.scss';

If you've read our previous articles, you're aware of the majority types of export declarations. In this piece, we'll discuss two of the following:

import useSelect from '@wordpress/data'; import useEntityProp from '@wordpress/core-data';

After you've imported the dependencies, inform us of what procedure that you'll useSelect and useEntityProp in Edit(). Edit() function:

const postType = useSelect( ( select ) => select( 'core/editor' ).getCurrentPostType(), [] ); const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
  • useEntityProp makes use of a custom hook that allows blocks to update and read the meta field on an article.  It's defined as a "hook that retrieves the value along with the setter for the property in the closest entity with the type specified". It will return "an array of which it is the main item that contains the value of the property, the second is the setter. The third item is the complete value object of the REST API. This provides additional details, like rendering, the raw, rendered and protected props". (See the API Updates and the General Block Editor API Updates.)

This code will provide the most postType in the current postType as an object in meta field ( meta) along with the setter function for updating the meta fields ( setMeta).

Replace the code currently by editing(). Edit() function with this code:

export default function Edit() const blockProps = useBlockProps(); const postType = useSelect( ( select ) => select( 'core/editor' ).getCurrentPostType(), [] ); const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' ); const bookTitle = meta[ '_meta_fields_book_title' ]; const bookAuthor = meta[ '_meta_fields_book_author' ]; const updateBookTitleMetaValue = ( newValue ) => setMeta( ...meta, _meta_fields_book_title: newValue ); ; const updateBookAuthorMetaValue = ( newValue ) => setMeta( ...meta, _meta_fields_book_author: newValue ); ; return ( ... ); 

Again:

  • We utilized the UseSelect tool to get the current kind of post.
  • useEntityProp provides an array of metadata fields as well as an option to set new meta fields.
  • updateBookTitleMetaValue and updateBookAuthorMetaValue are two event handlers to save meta field values.

The next stage is to generate your JSX (JavaScript XML) code that returns by the editing() function. Editor() function:

export default function Edit() ... return ( > ); 

The RichText component provides the option of an editing content input. TextControl is a simple text field. TextControl provides basic text fields.

Also, we have designed a sidebar with two input fields you can use to replace the two form controls which comprise the block.

Save the file, and go back to the editor. Include it in the Meta Fields Block using the block inserter , and add the title of the book and its author.

A custom block including two custom meta fields
A custom block created, using two customized meta fields.

If you modify the value that is entered in the text field in the block, the values in the text field which corresponds to the sidebar will be altered as well.

The next step is to create the PHP code that creates the HTML which will display at the front end.

The Block will be displayed on the Frontend

The primary PHP file is edited using your code editor. alter the function callback function that creates output from the block.

function meta_fields_metadata_block_block_init() register_block_type( __DIR__ . '/build', array( 'render_callback' => 'meta_fields_metadata_block_render_callback', ) ); add_action( 'init', 'meta_fields_metadata_block_block_init' ); function meta_fields_metadata_block_render_callback( $attributes, $content, $block ) $book_title = get_post_meta( get_the_ID(), '_meta_fields_book_title', true ); $book_author = get_post_meta( get_the_ID(), '_meta_fields_book_author', true ); $output = ""; if( ! empty( $book_title ) ) $output .= '' . esc_html( $book_title ) . ''; if( ! empty( $book_author ) )*if( strlen( $output ) > $output )// return "div  . get_block_wrapper_attributes() . '>' . $output . "/div>" Otherwise, return 'div  . get_block_wrapper_attributes() . '>' . '' . __( 'Sorry. There are no fields here!' ) . '' . '

';

This code is quite self-explanatory. First, we use the function get_post_meta to determine the values from the meta fields that we have constructed. We then use the value to generate the contents for the block. The callback function will return the HTML code of the block.

The block is now available to use. The code was deliberately left in this example as simple as we could, but by making use from Gutenberg's built-in components, it can be built into larger blocks and gain the maximum benefit out of WordPress custom meta fields.

A custom block including several meta fields
Custom block that includes many meta fields.

In the example we used the block we used the elements h3 and p elements to create the block which will serve as the frontend.

You are however able to display data in many different methods. This image depicts an unorganized table with meta fields.

An example block on the frontend
An example block within the frontend.

Find the entire programming code of this specific illustration inside this Gist, which is available to the public..

The addition of a custom Meta Box in the Sidebar of the Document Sidebar

Another option is to attach specific meta fields to your the content you post by using a plugin which creates options inside the Document Sidebar.

It's pretty similar to the one of the first example, however, in this instance, there is no need for a block in order to handle metadata. The component will be created to create a tab that contains a number of control in the Document sidebar following these instructions:

  1.       Block plugins can be created through the use of the create-block
  2.       Set up an HTML0 meta box to use with the Classic Editor
  3.       Integrate the meta fields inside the plugin's core file using Register_Post_Meta() function
  4.       Create a plugin inside index.js file. index.js file
  5.       Build the component using one of the included Gutenberg components

Make a Block Plugin Utilizing the tool Create-block

If you want to create a completely new block plug-in, follow the steps in the previous section. You can create the plugin from scratch, or alter the scripts that we built using the example that we previously.

Make a customized Meta Box to use the Classic Editor

The next step is you will need to register a custom meta box that can ensure compatibility with backwards compatible WordPress websites that are still running Classic Editor. Classic Editor. This procedure works exactly as the method described in the earlier section.

You must register for your Custom Meta Fields in the Main Plugin File

Following step is to add the custom meta fields into the main plugin file by using register_post_meta() function. register_post_meta() function. Again, you can apply the earlier method.

Create a plugin in the index.js File

After you've finished the preceding steps, you're now ready to make a plugin inside the index.js file to render your custom component.

Before registering the plugin create the component folder inside the plugin's src folder. In within the component folder, you will be required to build the latest MetaBox.js file. You can choose whatever name you feel would be appropriate for the part. Make sure you follow the ideal method of names for React.

Before moving on Install before you proceed, Install prior to proceeding. Install the @wordpress/plugins module by using the command line tool.

End the program (mac) after which you can install the module restart the process:

Cnpm install WordPress/plugins the npm installation

Then, you'll then open your index.js file of your plugin and insert the following instructions.

/** * Registers a plugin for adding items to the Gutenberg Toolbar * * @see https://developer.wordpress.org/block-editor/reference-guides/slotfills/plugin-sidebar/ */ import registerPlugin from '@wordpress/plugins'; import MetaBox from './components/MetaBox';

This code can be explained fairly easily. We'd however prefer to take the time to study two import declarations that are appropriate for those who don't have advanced React capabilities.

In the previous import statement, it was essential to wrap the name of the component within curly brackets. With the next import statement, we don't include the full name of the function isn't contained within curly brackets.

Next, register your plugin:

registerPlugin( 'metadata-plugin', render: MetaBox );

registerPlugin simply allows you to register a plug-in. It takes two parameters into account:

  • Unique string that identifies the plugin
  • The plugin has a setting. Make sure to note that render property is a setting in your plugin. render property should be set as a function that is acceptable.

Create the Component using Gutenberg's built-in Components

The time has come to develop React. React component. Navigate to the MetaBox.js file (or the name you want to use) and include the following import declaration:

import __ from '@wordpress/i18n'; import compose from '@wordpress/compose'; import withSelect, withDispatch from '@wordpress/data'; import PluginDocumentSettingPanel from '@wordpress/edit-post'; import PanelRow, TextControl, DateTimePicker from '@wordpress/components';
  • Create function performs function composition. Create function performs functions composition  in that the result from the function is transferred to another function.

Before you are able to begin using compose compose, you will require installing the appropriate module:

Install NPM @wordpress/compose save

It will be the compose function is available in just a second.

  • withSelect and withDispatch withDispatch are two higher order components which allow you to fetch or dispatch data from or into a WordPress store. withSelect allows you to add props that are state-based using withDispatch. With selectors, withDispatch is a way to share props with registered actions created by the creators.
  • PluginDocumentSettingPanel renders items in the Document Sidebar (see the source code on Github).

After that, you'll build the component that will display your meta box within the Document sidebar. In your MetaBox.js file, include the following code:

const MetaBox = ( postType, metaFields, setMetaFields ) => if ( 'post' !== postType ) return null; return( setMetaFields( _meta_fields_book_title: value ) /> setMetaFields( _meta_fields_book_author: value ) /> setMetaFields( _meta_fields_book_publisher: value ) /> setMetaFields( _meta_fields_book_date: newDate ) __nextRemoveHelpButton __nextRemoveResetButton /> ); const applyWithSelect = withSelect( ( select ) => return metaFields: select( 'core/editor' ).getEditedPostAttribute( 'meta' ), postType: select( 'core/editor' ).getCurrentPostType() ; ); const applyWithDispatch = withDispatch( ( dispatch ) => return setMetaFields ( newValue ) dispatch('core/editor').editPost( meta: newValue ) ); export default compose([ applyWithSelect, applyWithDispatch ])(MetaBox);

Let's look over the code.

  • The PluginDocumentSettingPanel element renders a new panel in the Document sidebar. It set the name ("Book details") and the icon and sets the opening to false, which means that initially the panel will not be opened until the.
  • Within the PluginDocumentSettingPanel we have three text fields and a DateTimePicker element that allows the user to set the publication date.
  • withSelect provides accessibility to the select function, which we're employing to fetch metaFields in addition to PostType. withDispatch gives accessibility to dispatch, which is the dispatch function, which permits the update of metadata values.
  • Additionally, the compose function lets us make our own components with withSelect and dispatch higher-order components. This lets the component have access to metaFields as well as the postType postType properties and also to use functions such as the settingMetaFields function.

Save your MetaBox.js file and create a new page for your WordPress web site for development. Then, look through the Document Sidebar. The user should be able look at the new book details section.

A custom meta box panel in Gutenberg
A custom meta box panel inside Gutenberg.

Now run your tests. Input the values for your meta fields that you have made and saved the page. After that you load the page, go back and see if the settings you set are there.

Incorporate the block that we made in the previous section. Make sure that all is working properly.

The addition of a custom sidebar for managing Meta-Data posts

If you're able to add a vast number of custom meta fields to add to your posts or the types of posts you have created it is possible to design a Custom Settings Sidebar specifically for the plugin.

It's a lot like to the earlier example. If you've mastered the steps discussed in the preceding section, you should not have issues creating a Custom Sidebar to Gutenberg.

Again:

  1.       Create a block-plugin by using create-block
  2.       Make an HTML0 meta box within the Classic Editor
  3.       Register the custom meta fields within the main plugin's files using Register_Post_Meta() function
  4.       Create a plugin within index.js file. index.js file
  5.       Make the component using the included Gutenberg components

Design a completely block with a brand new plugin using the tool to create blocks

If you're looking to build a new block plugin Follow the instructions above. Make a new block plugin or edit the scripts built in the earlier tutorials.

Make a customized Meta Box to use the Classic Editor

Register a customized meta box to ensure compatibility backwards with WordPress sites using Classic Editor. Classic Editor. The process is the same way as the one described in the first section.

Create your Custom Meta Fields in the Main Plugin File

Custom meta fields can be created in the plugin's file that contains it's register_post_meta() function.

Install a Plugin from the index.js File

Now create an unfilled CustomSidebar.js file in the components folder.

Then, you are able to edit the index.js file as the following:

/** * Registers a plugin for adding items to the Gutenberg Toolbar * * @see https://developer.wordpress.org/block-editor/reference-guides/slotfills/plugin-sidebar/ */ import registerPlugin from '@wordpress/plugins'; import CustomSidebar from './components/CustomSidebar'; // import MetaBox from './components/MetaBox'; registerPlugin( 'metadata-block', render: CustomSidebar );

Utilizing the following code, we first install our CustomSidebar component. We and then tell that the RegisterPlugin function what to show the component.

Create the component using built-in Gutenberg Components

Then, you can start by opening the CustomSidebar.js file and incorporate the following dependencies

import __ from '@wordpress/i18n'; import compose from '@wordpress/compose'; import withSelect, withDispatch from '@wordpress/data'; import PluginSidebar, PluginSidebarMoreMenuItem from '@wordpress/edit-post'; import PanelBody, PanelRow, TextControl, DateTimePicker from '@wordpress/components';

You should notice that we have two parts that are brand new:

  • PluginSidebar appears as an image in the Gutenberg Toolbar which clicks on it. It then displays a sidebar that includes all the information contained in the component (The element is described by GitHub). GitHub).
  • PluginSidebarMoreMenuItem renders a menu item under Plugins in More Menu dropdown and can be used to activate the corresponding PluginSidebar component (see also on GitHub).

Now you can design your own component:

const CustomSidebar = ( postType, metaFields, setMetaFields ) => if ( 'post' !== postType ) return null; return ( Metadata Sidebar setMetaFields( _meta_fields_book_title: value ) /> setMetaFields( _meta_fields_book_author: value ) /> setMetaFields( _meta_fields_book_publisher: value ) /> setMetaFields( _meta_fields_book_date: newDate ) __nextRemoveHelpButton __nextRemoveResetButton /> > ) 

The next stage is component composition with using the select and with dispatch other components that are ordered:

const applyWithSelect = withSelect( ( select ) => return metaFields: select( 'core/editor' ).getEditedPostAttribute( 'meta' ), postType: select( 'core/editor' ).getCurrentPostType() ; ); const applyWithDispatch = withDispatch( ( dispatch ) => return setMetaFields ( newValue ) dispatch('core/editor').editPost( meta: newValue ) ); export default compose([ applyWithSelect, applyWithDispatch ])(CustomSidebar);

It is possible to save the changes before checking the editor's interface. When you go to the Option menu, there's an up-to-date Metadata Sidebar option listed in the plugins section. If you click it, it'll allow users to enable your own custom sidebar.

The PluginSidebarMoreMenuItem component adds a menu item under Options - Plugins
The PluginSidebarMoreMenuItem component adds a menu item under Options - Plugins.

The same thing happens when you press the book icon located on the right hand side of the screen.

The Plugin Settings Sidebar
The Plugin settings Sidebar.

After that, visit your website for development and create an article on your blog. Fill in your meta fields and then upload blocks to the editor's canvas. Blocks must contain the same metadata fields that you've entered in your personal sidebar.

You can save the blog's post and view the page in the front end. The cards you get must include the title of your book and author's name as well as the name of the publisher as along with the date the book was published.

You'll find the full details of the article's code inside this accessible overview.

Additional Readings

This article has covered many aspects, from the selection of selectors to higher order components and much more. We've included the most popular sources we've used to reference throughout the article as well.

If you want to delve deeper into the subject, you may be interested in the following additional resources:

Gutenberg Documentation as well as official WordPress Documentation as well as Resources

Additional Official Resources

Additional Resources Available from the Community

Informational Readings from the Website

Summary

Now you should be able benefit from the possibilities of custom fields available in Gutenberg for creating more elaborate and useful WordPress websites.

However, there's more. With the information gained through our blog posts on blocks, you'll also be able to figure out what you can do to build React components that aren't part of WordPress. Since, Gutenberg is a React-based SPA.

The next step is up to you! Did you design Gutenberg blocks using custom meta fields? We would love to see your creations by leaving a comment below.

  • Simple setup and management on the My dashboard
  • Support is available 24/7.
  • The most effective Google Cloud Platform hardware and network is driven by Kubernetes to ensure the most efficient capacity
  • Enterprise-grade Cloudflare integration to speed up your business as well as security
  • Reaching the world's audience with over 35 data centers and 275+ PoPs worldwide

This post was first seen on here