如何修改 wp json api 媒体响应

How to modify wp json api media response

我正在尝试为“/media”端点的 wp json api 响应添加一个额外的字段。 在 doc 之后,我让它为“/posts”或“/pages”工作,但我不知道如何为“/media”端点添加一个字段。

所以(对于“/posts”或“/pages”)这是可行的:

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';
}

对于媒体,这是行不通的,到目前为止我已经试过了:

  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';
  }

我也尝试 'hooking' 进入其他过滤器(这样说是正确的吗?)

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 似乎可以解决问题。

最终目标是将字段 'srcset' 添加到媒体响应中

使用

wp json api : 版本 2.0-beta12

wordrpess:版本 4.4.2

如有任何帮助,我们将不胜感激。

您需要使用类型 attachment 而不是 media。这应该有效:

  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';
  }