By making WordPress post meta fields available via the REST API we can access these values from our JavaScript code. This also makes it easier to debug post meta in the block editor, as we can query the post meta directly from the browser console.
If you’re not sure how to make your post meta values available via the REST API, I have a separate blog post about this: Make WordPress Post Meta Available in REST API.
Read Post Meta
Want a quick look at the post meta values for the post you’re currently editing in the WordPress block editor? Open the browser console and run this command:
wp.data.select('core/editor').getCurrentPostAttribute('meta');
The above command returns an object of post meta fields attached to the current post. For example, the post meta for this post looks like this (not very exciting):
{
footnotes: "",
nf_dc_page: "",
_exactmetrics_sitenote_active: false,
_exactmetrics_sitenote_category: 0,
_exactmetrics_sitenote_note: "",
_mi_skip_tracking: false
}
While getCurrentPostAttribute gets the post meta fields saved to the database, we can also query getEditedPostAttribute, which may return some different values based on unsaved changes we’ve made to a post:
wp.data.select('core/editor').getEditedPostAttribute('meta');
Read a Single Post Meta Value
To retrieve a single post meta value instead of all the post meta for a post, we can append the field name to the end of the previous command. If we only want the value of the footnotes field, our command looks like this:
wp.data.select('core/editor').getCurrentPostAttribute('meta').footnotes;
In the case of the footnotes field, we saw in the previous example this will return an empty string.
Write Post Meta
Just as we can read post meta from our JavaScript code, we can also update those values in a similar way. Let’s say we’d like to update the _exactmetrics_sitenote_note field to “ryan’s test note”. We can do this by running the following command:
wp.data.dispatch('core/editor').editPost({meta:{_exactmetrics_sidenote_note:"ryan's test note"}});
Add a New Post Meta
We can use the same command from above to add a new post meta value. For example, we can add my_example_field and assign it a value of “ryan’s example value”:
wp.data.dispatch('core/editor').editPost({meta:{my_example_field:"ryan's example value"}});
This approach will add the post meta field and value only for the current post.
Saving Post Meta Changes
After updating post meta values from the console or our JavaScript code, we can save the changes in JavaScript as well:
wp.data.dispatch('core/editor').savePost();