When registering a new post meta field in WordPress we can make that field available via the REST API. While this doesn’t happen by default, it’s fairly simple to do.
Registering a Post Meta Field
The code to register a new post meta typically looks something like this:
<?php
register_post_meta( 'post', 'example_post_meta_field', [
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
},
'sanitize_callback' => 'sanitize_text_field',
'show_in_rest' => true,
'single' => true,
'type' => string
]);
The code above registers a new post meta field example_post_meta_field on posts of type ‘post’. The line ‘show_in_rest’ => true indicates this new post meta field should be made available via the REST API (but only for users who have permissions to ‘edit_posts’).
Usage with Custom Post Types
If you’re planning to use custom post meta on a custom post type, there is an additional consideration when registering your custom post type. In the register_post_type function call, you must include the ‘supports’ array within the args array. The ‘supports’ array must include ‘custom-fields’ in order for any custom post meta values applied to that post type to also appear via the REST API.
Example CPT Registration
<?php
register_post_type( 'books',
array(
'labels' => array(
'name' => __( 'Books' ),
'singular_name' => __( 'Book' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'books'),
'show_in_rest' => true,
'supports' => array(
'title',
'editor',
'author',
'custom-fields'
)
)
);
In the code above we register a ‘books’ post type, making sure to set ‘show_in_rest’ => true and making sure to include ‘custom-fields’ in the ‘supports’ array.
Let’s say we have our ‘books’ post type and we want to register a custom post meta value ‘publisher’. The code might look something like this:
<?php
register_post_meta( 'books', 'publisher', [
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
},
'sanitize_callback' => 'sanitize_text_field',
'show_in_rest' => true,
'single' => true,
'type' => string
]);
The ‘publisher’ post meta will now be accessible via the REST API for posts of the ‘books’ type.