<?php
function add_cpt_to_rest() {
global $wp_post_types;
$rest_post_types = [POST_TYPE_NAME1, POST_TYPE_NAME2];
foreach ($rest_post_types as $cpt_name) {
$wp_post_types[$cpt_name]->show_in_rest = true;
}
}
add_action( 'init', 'add_cpt_to_rest' );
<?php
add_action( 'rest_api_init', 'register_api_hook' );
function register_api_hook() {
$rest_post_types = [POST_TYPE_NAME1, POST_TYPE_NAME2]; // the field is added for these post types in the API
register_rest_field(
$rest_post_types,
'field_name_here',
array(
'get_callback' => 'return_field_name_here',
)
);
}
function return_field_name_here( $post, $field_name, $request ) {
// return for example user (author) meta based on the post object
$author_id = $post['author'];
$field_name = get_user_meta( $author_id, 'field_name', true );
return $field_name;
}