Managing post meta in WordPress has evolved significantly with the introduction of the Gutenberg block editor. This tutorial aims to simplify the process of enabling, reading, and updating custom post meta in the Gutenberg editor. By following these steps, you’ll gain a deeper understanding of how to work with post meta in the modern WordPress environment.
Enable: Granting REST API Access to Post Meta
By default, WordPress post meta fields are not accessible via the REST API. To enable REST API access for each post meta, the register_post_meta function must be used. It’s important to note that the post type must have “custom-fields” support enabled.
/**
* Registers the custom_post_meta field.
*
* @return void
*/
function register_custom_post_meta_field() {
register_post_meta(
'post',
'custom_post_meta',
[
'type' => 'string',
'show_in_rest' => true,
'single' => true,
]
);
}
add_action( 'init', 'register_custom_post_meta_field' );
Read: Retrieving Post Meta Value in the Gutenberg Block Editor
In the Gutenberg block editor, post data is managed through a Redux-like module called @wordpress/data. This module provides a straightforward method to read and access the custom post meta we registered earlier. Open your browser’s developer console and use the following code:
wp.data.select('core/editor').getEditedPostAttribute('meta');
To retrieve the value of the ‘custom_post_meta’ field:
wp.data.select('core/editor').getEditedPostAttribute('meta').custom_post_meta;
If you’re working within a custom block, you can utilize the following example code instead:
Create and Update: Modifying, Editing, and Saving Post Meta Values in the Gutenberg Block Editor
With the @wordpress/data module, modifying and saving post meta values becomes effortless. Dispatch a call to the registered reducer to update the state value. Use the following code as an example:
wp.data.dispatch('core/editor').editPost({ meta: { custom_post_meta: 'My Custom Post Meta Value' } });
For a more detailed example within a custom block, you can utilize the following code:
Conclusion
With the Gutenberg block editor, managing post meta in WordPress has become more streamlined. By enabling REST API access, reading post meta values, and updating them using the @wordpress/data module, you can effectively work with custom post meta in the Gutenberg editor. The example provided demonstrates a simple custom block that allows you to modify and save post meta values conveniently.
By following these techniques, you can leverage the power of the WordPress Block Editor to enhance your website’s functionality and provide a richer user experience.
Leave a Reply