WP API Response does not show my registered metadata
-
20-05-2021 - |
Question
I am trying to get metadata from a custom post type splash_location
however it's not showing up in my response. I have registered my metatag splash_location_title
but it doesn't show up in my JSON request.
function splash_location_custom_post_type() {
register_post_type('splash_location',
array(
'labels' => array(
'name' => __('Locations', 'textdomain'),
'singular_name' => __('Location', 'textdomain'),
),
'supports' => array( 'title', 'custom-fields' ),
'menu_icon' => 'dashicons-admin-page',
'public' => true,
'has_archive' => true,
'show_in_rest' => true,
)
);
}
add_action('init', 'splash_location_custom_post_type');
$meta_args = array(
'type' => 'string',
'description' => 'A meta key associated with a string meta value.',
'single' => true,
'show_in_rest' => true,
);
register_meta( 'splash_location', 'splash_location_title', $meta_args );
//Code in my block file to get splash_location data
const getLocationPosts = () => axios
.get('/wp-json/wp/v2/splash_location/')
.then(response => {
const { data } = response
console.log(data)
})
Solution
For posts (Posts, Pages and custom post types), the very first parameter for register_meta()
is always post
and to set a custom post type, use the object_subtype
argument in the third parameter like so:
$meta_args = array(
'object_subtype' => 'splash_location', // the post type
'type' => 'string',
'description' => 'A meta key associated with a string meta value.',
'single' => true,
'show_in_rest' => true,
);
register_meta( 'post', 'splash_location_title', $meta_args );
Or you could instead use register_post_meta()
which accepts the post type as the first parameter:
$meta_args = array(
'type' => 'string',
'description' => 'A meta key associated with a string meta value.',
'single' => true,
'show_in_rest' => true,
);
register_post_meta( 'splash_location', 'splash_location_title', $meta_args );
So in your existing code, you'd simply replace the register_meta
with register_post_meta
.. 🙂
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange