I'm trying to add an extra field to the wp json api reponse for the '/media' endpoint. Following the doc, I have it working for '/posts' or '/pages', but I cannot figure out how to add a field for the '/media' endpoint.
So (for '/posts' or '/pages') this works :
add_action( 'rest_api_init', 'np_register_extra_field' );
function np_register_extra_field() {
register_rest_field( 'post',
// register_rest_field( 'page', // this works too
'extra_media_field',
array(
'get_callback' => 'np_get_extra_field',
'update_callback' => null,
'schema' => null,
)
);
}
function np_get_extra_field( $object, $field_name, $request ) {
return 'foobar';
}
For media, this does not work, so far I've tried like this :
add_action( 'rest_api_init', 'np_register_extra_field' );
function np_register_extra_field() {
register_rest_field( 'media',
'extra_media_field',
array(
'get_callback' => 'np_get_extra_field',
'update_callback' => null,
'schema' => null,
)
);
}
function np_get_extra_field( $object, $field_name, $request ) {
return 'foobar';
}
I also tried 'hooking' into other filters (is that a correct way to say that ?)
add_action( 'rest_media_query', 'np_register_extra_field' );
add_action( 'rest_pre_insert_media', 'np_register_extra_field' );
add_action( 'rest_prepare_attachment', 'np_register_extra_field' );
None of those seems to do the trick.
the endgoal is to add the field 'srcset' to the media response
Using
wp json api : Version 2.0-beta12
wordrpess : version 4.4.2
Any help would be appreciated.
You need to use the type attachment
instead of media
. This should work:
add_action( 'rest_api_init', 'np_register_extra_field' );
function np_register_extra_field() {
register_rest_field( 'attachment',
'extra_media_field',
array(
'get_callback' => 'np_get_extra_field',
'update_callback' => null,
'schema' => null,
)
);
}
function np_get_extra_field( $object, $field_name, $request ) {
return 'foobar';
}