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

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