Expose a custom field of a custom post type to the REST API

Question

I added a custom field to posts and exposed it to the REST API, which works for standard posts and appears in the APIs response. But does not work for a custom post type (projects) which is basically a standard post type just with a different name. The field is present in the project post type and I can edit and save it.

How can I register it to both post and the custom “project” post type? I guess I simply need to register it the same way as shown below. Can I register it to both types at once? This is how I register it for posts. The reference show that the $object_type is an array, so if I am not totally wrong, it should be possible, but how does it work?

/**********************************************
* Add featured video to REST API
***********************************************/
function add_featured_video_id() {
    register_rest_field(
    'post', 
    'featured_video_id',
    array(
        'get_callback'    => 'get_featured_video_id',
        'update_callback' => null,
        'schema'          => null,
         )
    );
}

add_action( 'rest_api_init', 'add_featured_video_id' );
    function get_featured_video_id( $object, $field_name, $request ) {
        $fv_id= get_post_meta(get_the_ID(), '_chrest_featured_video', true);
    return $fv_id;
}
0
, Carsten H 2 years 2020-01-04T08:38:49-05:00 0 Answers 79 views 0

Leave an answer

Browse
Browse