Make Post Meta Field Accessible via REST API
By default WordPress post meta fields are not accessible via the WordPress REST API. To make it accessible we need to add the following PHP code to our site. This code registers our post meta field as accessible via the REST API for users who can edit posts.
I’ve added the following in a file in the mu-plugins directory (i.e. at wp-content/mu-plugins/salcode-example-post-meta.php
).
<?php
add_action( 'init', 'salcode_example_register_post_meta' );
function salcode_example_register_post_meta() {
$post_type = 'post';
register_post_meta( $post_type, 'salcode_example', [
'auth_callback' => function() {
return current_user_can('edit_posts');
},
'sanitize_callback' => 'sanitize_text_field',
'show_in_rest' => true,
'single' => true,
'type' => 'string',
]);
}
CPT Must Support ‘custom-fields’
When the Custom Post Type (CPT) is defined the array of supports
values must include custom-fields
. e.g.
'supports' => array( 'title', 'editor', 'custom-fields' ),
If custom-fields
is not included, post meta via the REST API will not work.
Using Gutenberg Methods from the Browser Console
Opening the browser console, we can run lines of JavaScript. If we are on a page with the Gutenberg editor, we can interact with the editor with these lines of JavaScript.
While using the editor we may change some meta values in the editor and these changes will only exist in the editor (not in the database). Saving the post will save these changes in the database.
Values in the Editor
These are the latest values in the editor (some of these values may not be saved to the database yet).
wp.data.select('core/editor').getEditedPostAttribute('meta');
To get just the value of salcode_example
we can use
wp.data.select('core/editor').getEditedPostAttribute('meta').salcode_example;
Values in the Database
These are the values as they are stored in the database (as of the last time the editor communicated with the database, e.g. on initial load or when a post was saved).
wp.data.select('core/editor').getCurrentPostAttribute('meta')
To get just the value of salcode_example
we can use
wp.data.select('core/editor').getCurrentPostAttribute('meta').salcode_example
Modify the Values in the Editor
This command allows us to modify values in the editor (but it does not store these values to the database, savePost
does that).
wp.data.dispatch('core/editor').editPost({meta: {salcode_example: 'My apple'}})
Save the Values in the Editor to the Database
wp.data.dispatch('core/editor').savePost();
After running this command, the values returned by getEditedPostAttribute()
and getCurrentPostAttribute()
will be the same (i.e. the data in the editor will be in sync with the data in the database).
Hello Sal,
I’m using an SEO plugin that stores SEO data for each post. When I’m trying to console.log the post meta that SEO data isn’t shown. Is it because the REST API isn’t enabled for that post meta data?
Could you advise on how to properly enable it?