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)
})
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.. 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0