In WordPress Environment, Metaboxes are a great way to add custom fields to the post. They can be used to add and display all sorts of information, such as post data, product information, event details, or user preferences.

What is metabox –

Metaboxes are typically used to extend the functionality of WordPress and provide users with a way to input and manage custom data associated with a post, page, or any custom post type (CPT).

In the past, metaboxes were created using PHP and added to the post editor using the add_meta_box() function. However, with the introduction of the Gutenberg block editor as a part of WordPress 5.0, WordPress now provides a new way to create metaboxes using the PluginSidebar component built with ReactJS.

The new PluginSidebar component is super flexible and you can build almost every type of setting that you want for metabox easily.

Note – Although designs related to metaboxes are allowed in the theme, it’s recommended that all meta boxes/custom fields are added via a plugin.

If you are going to create a new metabox from scratch, then no issue, but if you are looking to migrate an existing old metabox (built with PHP) into a new metabox, then you have to follow a few things I’ll mention later in this post.

Register Custom Meta Field

First of all, you need to register your meta field using the register_meta function. Below is the example code for how you can register custom meta fields. You can add more fields in the argument based on your requirement by following the register_meta function.

If you are migrating your old metabox to a new one, then must keep the meta field key the same or add support for your old meta fields.

for example, in the old metabox, it is prefix_my_seo_title then in the new metabox, it must be the same prefix_my_seo_title.

function prefix_register_meta() {

    $args = array(
        'type'           => 'string',
        'default'        => 'Custom Meta field',
        'single'         => true,
        'show_in_rest'   => true,
        'auth_callback'  => '__return_true',
    );

    // Register meta.
    register_meta( 'post', 'custom_meta_key', $args );
}

add_action( 'init', 'prefix_register_meta' );

Note* – When you add custom fields in your post, must add the support for custom-fields for your CPT if it is not enabled by default. If you don’t, then the new settings will not work because there will be no registered custom meta fields.

If it is coming from a theme or plugin, then you can enable custom field support by adding the below code –

/**
 * Add 'custom-fields' support for a post type
 *
 * @param array  $args      Ppost type arguments.
 * @param string $post_type Slug of the current post type.
 *
 * @return array Modified post type arguments.
 */
function add_custom_field_support( $args, $post_type ) {

    // Check if 'custom-fields' support already exists.
    if ( 'example-cpt' === $post_type ) {
        $args['supports'][] = 'custom-fields';
    }

    return $args;
}

add_filter('register_post_type_args', 'add_custom_field_support', 10, 2 );

Now it’s time to jump into ReactJS code to create our awesome new metabox.

Register Metabox Using PluginSidebar

Before adding code let’s add a quick setup environment for development by installing a few npm packages required to build a new metabox using the PluginSidebar.

1. Create a package.json file in your project root folder and add the below code to it.

{
    "name": "eramits-metabox",
    "version": "1.0.0",
    "description": "My custom metabox",
        "scripts": {
        "build": "wp-scripts build src/index.js --output-path=assets",
        "start": "wp-scripts start src/index.js --output-path=assets",
        "lint:js": "wp-scripts lint-js",
        "lint:pkg-json": "wp-scripts lint-pkg-json"
    },
    "devDependencies": {
        "@wordpress/block-editor": "^12.4.0",
        "@wordpress/components": "^25.1.0",
        "@wordpress/data": "^9.5.0",
        "@wordpress/element": "^5.12.0",
        "@wordpress/hooks": "^3.35.0",
        "@wordpress/i18n": "^4.35.0",
        "@wordpress/scripts": "^26.6.0"
    }
}

now run the npm command to install the required packages that will be used to create metabox.

# using npm
npm install

# using pnpm
pnpm install

# using yarn
yarn install

Now you are set. Create a src folder in the project root folder and add all your uncompiled files here.

let’s create an index.js and style.scss file in the src folder. it will hold all js files.

import './plugin-sidebar';
import './style.scss';

style.scss file is to add any css if you want to style your metabox. After adding all these things, run npm run start in your command tool to watch the changes.

Let’s create a new js file called plugin-sidebar.jsx which will contain the code for sidebar metabx.

Add the below code in this file to register the new metabox using the plugin sidebar.


import { __ } from '@wordpress/i18n';
import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar } from '@wordpress/edit-post';
import { PanelBody } from '@wordpress/components';
import { cog } from '@wordpress/icons';

function RegisterMetabox() {

    return(
        <PluginSidebar name="eramits-post-metabox" title={ __( 'My Custom Metabox', 'eramits-metabox' ) }  icon={ cog }>
            <p>{ __( 'Plugin Sidebar', 'eramits-metabox' ) }</p>
        </PluginSidebar>
    );
}

registerPlugin(
    'eramits-post-metabox', {
        render: RegisterMetabox
    }
);

the name attribute should be unique. In the above example, the name attribute is eramits-post-metabox that is used in the registerPlugin function to render the component.

Enqueue files and stylesheet

Since you have added the basic code, just type npm run build in your command tool to generate the compiled JS and stylesheet files. It will create files in the defined path in package.json file.

Now enqueue it in the wp-admin area. To do this we will use the hook enqueue_block_editor_assets. It only loads the files in the block editor area where we needed it.

/**
 * Enqueque Editor Scripts
 */
function metabox_enqueue_assets() {

    // Return if widget page.
    if ( get_current_screen()->base === 'widgets' ) {
        return;
    }

    $plugin_url  = plugin_dir_url( __FILE__ );
	$plugin_path = plugin_dir_path( __FILE__ );

    $path  = $plugin_url . 'assets/';
    $asset = require $plugin_path . 'assets/index.asset.php';
    $deps  = $asset['dependencies'];

    wp_register_script(
        'eramits-metabox',
        $path . 'index.js',
        $deps,
        filemtime( $plugin_path . 'assets/index.js' ),
        true
    );

    wp_enqueue_style(
        'eramits-metabox',
        $path . 'style-index.css',
        array(),
        filemtime( $plugin_path . 'assets/style-index.css' )
    );

    wp_enqueue_script( 'eramits-metabox' );
}

add_action( 'enqueue_block_editor_assets', 'metabox_enqueue_assets' );

Now you have created the metabox for your site successfully. Activate your plugin in which you have added all these codes, and go to Dashboard > Posts > Edit a post.

In the right top corner, you will see a little setting (cog) icon. Click on it to open your newly created metabox area.

You can clearly see the metabox area has been created successfully. Now you have to add settings here.

Add Settings in PluginSidebar

Let’s start adding setting fields for the metabox. @wordpress/components package has all the necessary components that you will need to add settings. If you want any complex setting field like dimension, responsive range slider, etc, you can create custom components too.

If you need help to create a custom component, just drop a message using the contact form on the contact page.

Let’s stick to post, add the necessary lines to get and save the settings –

import { useSelect, useDispatch } from '@wordpress/data';

 const meta = useSelect( ( select ) =>
    select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {}
);

const setMeta = useDispatch( 'core/editor' );

Add the above function before the return function in the main function in the plugin-sidebar.jsx file.

<TextControl
    label={ __( 'Custom Post Title', 'eramits-metabox' ) }
    value={ meta['custom_meta_key'] }
    onChange={ ( value ) => {
        setMeta.editPost( {
            meta: {
                'custom_meta_key': value
            },
        } );
    } }
/>

Similarly, you can register and add as many settings as you need for your project. Now you can see the register field in your editor dashboard.

You can see I have added three fields to store the custom meta value. You can use the PanelBody component to organize your settings in groups.

Below is the complete code for the plugin-sidebar.jsx file –


import { __ } from '@wordpress/i18n';
import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar } from '@wordpress/edit-post';
import { cog } from '@wordpress/icons';
import { useSelect, useDispatch } from '@wordpress/data';
import {
    Button,
    ButtonGroup,
	TextControl,
    SelectControl,
	RangeControl,
	BaseControl
} from "@wordpress/components";

function RegisterMetabox() {

    const meta = useSelect( ( select ) =>
        select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {}
    );

    const setMeta = useDispatch( 'core/editor' );

    return(
        <PluginSidebar name="eramits-metabox" title={ __( 'My Custom Metabox', 'eramits-metabox' ) }  icon={ cog }>
            <div className='metabox-area'>
                <TextControl
                    label={ __( 'Custom Post Title', 'eramits-metabox' ) }
                    value={ meta['custom_meta_key'] }
                    onChange={ ( value ) => {
                        setMeta.editPost( {
                            meta: {
                                'custom_meta_key': value
                            },
                        } );
                    } }
                />
            </div>
        </PluginSidebar>
    );
}

registerPlugin(
    'eramits-metabox', {
        render: RegisterMetabox
    }
);

It’s done. You have successfully added the metabox using the block editor PluginSidebar component.

How To Display the Meta Settings

To display the custom meta field in the PHP template, you can use the get_post_meta function. To read more about the get post meta function, follow this reference link.

See the below example code to get the post meta-

get_post_meta( get_the_ID(), 'custom_meta_key', true );

Wrapping up

By following the above steps, you can easily create a metabox or migrate from an existing PHP metabox to a new super flexible metabox.

Since there are lots of things that have been changed in WordPress. It is not too late to adopt new methods, since WordPress is shifting its gear to Javascript.

Creating metaboxes using the pluginSidebar component is a new and improved way to add custom fields to the WordPress post editor. It is easier to use and maintain metaboxes using React, and metaboxes created using pluginSidebar are more compatible with the Gutenberg block editor.

If you are creating new metaboxes for your WordPress site, I recommend using the pluginSidebar component. It is the future of metabox development in WordPress.

Feel free to get in touch or leave a comment if you have doubts, suggestions, or any feedback related to this post. Don’t forget to let me know if it helps you.

Thank you for staying here. Have a nice day!

Leave a Reply

Your email address will not be published. Required fields are marked *