Is it possible to nest the JSON result of WordPress REST API?

I have been try to search around if it is possible to have a ‘nested’ JSON response in adding some custom fields through register_rest_field

I have this code:

function video_get_post_meta($object, $field_name, $request){
    return get_post_meta($object['id'], $field_name, true); 
}

function video_update_post_meta($value, $object, $field_name){
    return update_post_meta($object['id'], $field_name, $value); 
}

add_action('rest_api_init', function(){
    register_rest_field('post', 'length', 
        array(
            'get_callback' => 'video_get_post_meta', 
            'update_callback' => 'video_update_post_meta', 
            'schema' => null
        )
    );
    register_rest_field('post', 'file_name', 
        array(
            'get_callback' => 'video_get_post_meta', 
            'update_callback' => 'video_update_post_meta', 
            'schema' => null
        )
    );    
    register_rest_field('post', 'thumbnail', 
        array(
            'get_callback' => 'video_get_post_meta', 
            'update_callback' => 'video_update_post_meta', 
            'schema' => null
        )
    );
    register_rest_field('post', 'video_url', 
        array(
            'get_callback' => 'video_get_post_meta', 
            'update_callback' => 'video_update_post_meta', 
            'schema' => null
        )
    );    
});

This gives me a result like:

"length": "100",
"file_name": "video_test.mp4",
"thumbnail_": "https://example.com/the_thumb.jpg",
"video_url": "https://example.com/media/20180228.mp4",

But I am wondering if it is possible to have the response format like instead:

"video": {
    "length": "100",
    "file_name": "video_test.mp4",
    "thumbnail_": "https://example.com/the_thumb.jpg",
    "video_url": "https://example.com/media/20180228.mp4"
},

1 Answer
1

Use below code snippet

  function video_get_post_meta($object, $field_name, $request) {
       return array(
        'video' => array(
               ‘length’ => get_post_meta($object['id'], ‘length’, true),
               ‘file_name’ => get_post_meta($object['id'], ‘file_name’, true),
               ‘thumbnail_’ => get_post_meta($object['id'], ‘thumbnail_’, true),
               ‘video_url’ => get_post_meta($object['id'], ‘video_url’, true),
            ));
  }

  add_action('rest_api_init', function() {
       register_rest_field('post', 'video', 
           array(
               'get_callback' => 'video_get_post_meta', 
               'update_callback' => 'video_update_post_meta', 
               'schema' => null
           )
       );
 }

Output should be

"video": {
   "length": "100",
   "file_name": "video_test.mp4",
   "thumbnail_": "https://example.com/the_thumb.jpg",
   "video_url": "https://example.com/media/20180228.mp4"
},
    
   

Leave a Comment