Custom Meta Boxes Using the WordPress Block Editor (Gutenberg)

Custom meta boxes were used to expand the editor prior to the block editor. There are new options to extend with the new editor, providing developers greater freedom and authors a better experience. It is recommended that existing custom meta boxes be ported to one of these new approaches to provide a more uniform and consistent experience for people using the editor.

There are two methods for creating similar functionality to meta boxes in the block editor.

  1. Store Post meta with block
  2. Store post meta by creating sidebar for your plugin

Note: To save extra data with a post, the first way is to utilize Blocks. The data is saved in a post meta field, which works similarly to how meta boxes do.

1. Store Post Meta with Block

The serialized block HTML is where blocks often keep their attribute values. You may, however, build a block that stores its attribute values as post meta, which you can access programmatically from anywhere in your template.

In this little tutorial, you’ll learn how to make one of these blocks that asks a user for a single value and saves it as post meta.

You’ll need a plugin to hold your code before you begin this lesson. For details on how to set up a plugin, please see the first two stages of the Gutenberg Block Editor.

And here are the steps you have to follow:

How To Register Meta Field ?

A post meta field is a WordPress object for storing additional information about a post. Before you can utilize a new meta field, you must first register it. To learn more about post meta, see Managing Post Metadata.

Take notice of the show_in_rest parameter while registering the field. This guarantees that the data is loaded and saved through the REST API, which is used by the block editor. For further details, see the register_post_meta function specification.

In order for the register_post_meta function to operate, your post type must also allow custom-fields.

Create a PHP plugin file named softhunt-meta-block.php that contains the following code:

<?php
/**
 * Plugin Name: Meta Block
 */
 
// register custom meta tag field
function softhunt_register_post_meta() {
    register_post_meta( 'post', 'softhunt_meta_block_field', array(
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
    ) );
}
add_action( 'init', 'softhunt_register_post_meta' );
Note: WordPress considers a meta key protected if its name begins with an underscore. Passing a permission check, which is configured as the auth_callback in the register_post_meta function, is required to edit this field. Here's an example:
register_post_meta( 'post', '_softhunt_protected_key', array(
    'show_in_rest' => true,
    'single' => true,
    'type' => 'string',
    'auth_callback' => function() {
        return current_user_can( 'edit_posts' );
    }
) );

How To Create Meta Block ?

After you’ve registered the meta field in the previous step, you’ll need to construct a new block to show the user the value of the field.

The TextControl component, which is comparable to an HTML input text field, will be used for this block. Check out the Component Reference for more components.

Blocks can use the useEntityProp hook to obtain or update meta data.

Add the following code to your JavaScript file (we’ll call it softhunt.js in this tutorial):

With ES5:

( function ( wp ) {
    var el = wp.element.createElement;
    var registerBlockType = wp.blocks.registerBlockType;
    var TextControl = wp.components.TextControl;
    var useSelect = wp.data.useSelect;
    var useEntityProp = wp.coreData.useEntityProp;
    var useBlockProps = wp.blockEditor.useBlockProps;
 
    registerBlockType( 'softhunt/meta-block', {
        title: 'Meta Block',
        icon: 'smiley',
        category: 'text',
 
        edit: function ( props ) {
            var blockProps = useBlockProps();
            var postType = useSelect( function ( select ) {
                return select( 'core/editor' ).getCurrentPostType();
            }, [] );
            var entityProp = useEntityProp( 'postType', postType, 'meta' );
            var meta = entityProp[ 0 ];
            var setMeta = entityProp[ 1 ];
 
            var metaFieldValue = meta[ 'softhunt_meta_block_field' ];
            function updateMetaValue( newValue ) {
                setMeta(
                    Object.assign( {}, meta, {
                        softhunt_meta_block_field: newValue,
                    } )
                );
            }
 
            return el(
                'div',
                blockProps,
                el( TextControl, {
                    label: 'Meta Block Field',
                    value: metaFieldValue,
                    onChange: updateMetaValue,
                } )
            );
        },
 
        // No information saved to the block
        // Data is saved to post meta via attributes
        save: function () {
            return null;
        },
    } );
} )( window.wp );

With ESNext:

import { registerBlockType } from '@wordpress/blocks';
import { TextControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { useBlockProps } from '@wordpress/block-editor';
 
registerBlockType( 'softhunt/meta-block', {
    title: 'Meta Block',
    icon: 'smiley',
    category: 'text',
 
    edit( { setAttributes, attributes } ) {
        const blockProps = useBlockProps();
        const postType = useSelect(
            ( select ) => select( 'core/editor' ).getCurrentPostType(),
            []
        );
        const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
        const metaFieldValue = meta[ 'softhunt_meta_block_field' ];
        function updateMetaValue( newValue ) {
            setMeta( { ...meta, softhunt_meta_block_field: newValue } );
        }
 
        return (
            <div { ...blockProps }>
                <TextControl
                    label="Meta Block Field"
                    value={ metaFieldValue }
                    onChange={ updateMetaValue }
                />
            </div>
        );
    },
 
    // No information saved to the block
    // Data is saved to post meta via the hook
    save() {
        return null;
    },
} );
Important:  You must first enqueue your JavaScript file and its dependencies before testing. wp.element, wp.blocks, wp.components, wp.data, and wp.coreData are the WordPress packages mentioned above. Each of these must be included in the dependents list. Add the enqueue function to the softhunt-meta-block.php file:
function mysofthunt_enqueue() {
         wp_enqueue_script(
         'softhunt-script',
         plugins_url( 'softhunt.js', __FILE__ ),
         array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-data', 'wp-core-data', 'wp-block-editor' )
    );
}
add_action( 'enqueue_block_editor_assets', 'mysofthunt_enqueue' );

You may now add a Meta Block to a draught post and edit it. You’ll see your field, which you may fill in with a value. The post meta value will be kept whether you save the post as a draught or published. You may check by saving and reloading your draught to see whether the form is still filled in.

meta_block

You can also double-check that the data was saved by looking in the database table wp_postmeta and seeing if the new post id has the new field data.

How To Use Post Meta Data – Custom Meta Boxes

You may utilize the post meta data you saved in the previous step in a variety of ways.

  • How To Use Post Meta In PHP ?

The first example appends the post meta field value to the end of the post content, which is enclosed in an H4 tag. WordPress 5.0 does not modify this PHP technique.

function mysofthunt_content_filter( $content ) {
    $value = get_post_meta( get_the_ID(), 'softhunt_meta_block_field', true );
    if ( $value ) {
        return sprintf( "%s <h4> %s </h4>", $content, esc_html( $value ) );
    } else {
        return $content;
    }
}
add_filter( 'the_content', 'mysofthunt_content_filter' );
  • How To Use Post Meta In PHP ?

The post meta data can also be use in other blocks. The data is load at the conclusion of each paragraph block when it is display, that is when it is visible to the user in this case. As needed, you may swap this out for any core or custom block type.

When the block is display in PHP, use the register_block_type method to establish a callback that includes the meta value.

function softhunt_render_paragraph( $block_attributes, $content ) {
    $value = get_post_meta( get_the_ID(), 'softhunt_meta_block_field', true );
    // check value is set before outputting
    if ( $value ) {
        return sprintf( "%s (%s)", $content, esc_html( $value ) );
    } else {
        return $content;
    }
}
 
register_block_type( 'core/paragraph', array(
    'api_version' => 2,
    'render_callback' => 'softhunt_render_paragraph',
) );

Finishing Touches – Custom Meta Boxes

One disadvantage of utilizing a meta block is that it is simple for an author to forget about it because it must be insert into each post. The solution is to use block templates. A block template is a collection of block elements for each post type that has been pre-define. You may provide a default starting state for a post type using templates.

For this example, You can use a template to automatically insert the meta block at the beginning of a post.


Add the following code, To the softhunt-meta-block.php file:

function mysofthunt_register_template() {
    $post_type_object = get_post_type_object( 'post' );
    $post_type_object->template = array(
        array( 'softhunt/meta-block' ),
    );
}
add_action( 'init', 'mysofthunt_register_template' );

You may also include other block types in the array, such as placeholders, or restrict a post to a certain set of blocks. For additional information, check the documentation linked above. Templates are a great tool for customizing the editing experience.

For Store post meta by creating a sidebar for your plugin click the link…

That’s all for this article if you have any queries please contact us through our website or email us at softh[email protected]

Leave a Comment