The other day I needed to quickly retrieve the meta of a post without having an easy access to the server to use wp cli, or run a database query. Luckily, there is an easy way to get this information using your browser console, while you’re logged in and editing the post.
wp.data.select('core/editor').getEditedPostAttribute( 'meta' );
There’s a few things that need to be in place for this to work with custom post types.
As this helpful GitHub comment suggests, make sure that you register your custom post type with show_in_rest
set to true
and add support for custom-fields
.
register_post_type( 'my_post_type', array(
'labels' => array( 'name' => 'My Post Type' ),
function register_post_type(){
register_post_type( 'my_post_type', array(
'labels' => array( 'name' => 'My Post Type' ),
'public' => true,
'supports' => [ 'title', 'editor', 'custom-fields' ],
'show_in_rest'=>true
) );
}
add_action( 'init', 'register_post_type' );
And you also need to register your meta, as detailed in this css-tricks.com tutorial.
function register_post_meta(){
register_meta( 'post', 'my_post_meta', array(
'show_in_rest' => true,
'type' => 'string',
'single' => true,
) );
}
add_action( 'init', 'register_post_meta' );
And there you go. And if you’d like to see the full post object, you can use this:
wp.data.select('core/editor').getCurrentPost();
Here’s a quick summary of relevant functions:
/* Get post data */
wp.data.select('core/editor').getCurrentPost();
/* Get post meta */
wp.data.select('core/editor').getEditedPostAttribute('meta');
/* Update post data */
wp.data.dispatch('core/editor').editPost({/* POST DATA OBJECT */});
/* Example: */
wp.data.dispatch('core/editor').editPost({
title: 'New post title'
});
/* Update post meta */
wp.data.dispatch('core/editor').editPost({
meta:{
meta_key: 'meta value'
}
});