2

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.

Denis Florkin
  • 33
  • 1
  • 8

1 Answers1

0

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';
  }
herrstucki
  • 258
  • 1
  • 3
  • Thanks @herrstucki. You're right, that's what I end up doing and it works. – Denis Florkin Dec 29 '16 at 19:01
  • Can you answer how one can modify the wp-json response for a specific post only See: https://stackoverflow.com/questions/49330395/how-to-modify-title-in-wp-json-response-but-only-for-a-specific-post – James Hawkins Mar 18 '18 at 23:43