I’ve been writing blocks and various plugins for WordPress’ Block Editor, aka Gutenberg, for the past few years. So far the most frustrating thing has been to manage meta values.

There are many ways to do it, including Backbone API, data store, and Rest API directly.

To make things easier and consistent, I recently wrote a small useMeta hook to make the process easier.

/**
* WordPress dependencies.
*/
import { useDispatch, useSelect } from '@wordpress/data';
/**
* useMeta Hook.
*
* useMeta hook to get/update WordPress' meta fields.
*
* Meta field needs to be registered to REST using `register_post_meta` function.
*
* This will return an array of all the meta fields and you return an object of meta values.
* const [ metaValue, changeMetaValue ] = useMeta();
*
* If you want to get/change a particular meta field then you can pass the key as argument.
* const [ metaValue, changeMetaValue ] = useMeta( 'meta_key' );
*
* @see https://developer.wordpress.org/reference/functions/register_post_meta/
* @author Hardeep Asrani <hardeepasrani@gmail.com>
* @version 1.0
*
*/
const useMeta = key => {
const metaValue = useSelect( select => {
const { getEditedPostAttribute } = select( 'core/editor' );
if ( undefined === key ) {
return getEditedPostAttribute( 'meta' );
}
return getEditedPostAttribute( 'meta' )[ key ] || '';
}, [ key ] );
const { editPost } = useDispatch( 'core/editor' );
const changeMetaValue = value => {
if ( undefined === key ) {
return editPost( {
meta: {value },
} );
}
return editPost( {
meta: {
[ key ]: value
},
} );
};
return [ metaValue, changeMetaValue ];
};

view raw
useMeta.js
hosted with ❤ by GitHub