Follow: https://v2.wp-api.org/extending/modifying/#examples
Example working with me
/*
* add field list_chap to post
*/
add_action( 'rest_api_init', 'hdh_register_post' );
function hdh_register_post() {
register_api_field( 'post',
'list_chap',
array('get_callback' => 'hdh_get_list_chapter' ,
'update_callback' => null,
'schema' => null,)
);
}
function hdh_get_list_chapter($object, $field_name, $request){
wp_reset_postdata();
wp_reset_query();
$connected = new WP_Query( array(
'connected_type' => 'post_to_chapter',
'connected_items' => $object['id'],
'nopaging' => true
) );
$list_chap = array();
// Display connected pages
if ( $connected->have_posts() ) {
while ( $connected->have_posts() ) {
$connected->the_post();
$chap['title'] = get_the_title(get_post()->p2p_to);
$chap['link'] = get_the_permanlink(get_post()->p2p_to);
array_push($list_chap, $chap) ;
}
// Prevent weirdness
wp_reset_postdata();
}
return $list_chap;
}