我找到了解决问题的办法。媒体的对象类型不是media
, 只是attachment
. 因此,以下代码对我有效:
<?php
/**
* Plugin Name: REST Response Modifier
* Description: A simple plugin to modify the rest api
* Author: TheBalco
* Author URI: http://somepage.dev
*/
add_action(\'rest_api_init\', \'tb_add_custom_rest_fields\');
function tb_add_custom_rest_fields() {
// schema
$media_category_schema = array(
\'description\' => \'Categories of the media item\',
\'type\' => \'string\',
\'context\' => [\'view\']
);
// registering the field
register_rest_field(
\'attachment\',
\'media_category\',
[
\'get_callback\' => \'get_media_category\',
\'update_callback\' => null,
\'schema\' => $media_category_schema
]
);
}
/**
* Callback
* @param array $object The current post object
* @param string $field_name The name of the field
* @param WP_REST_request $request The current request
* @return string The return value
*/
function get_media_category($object, $field_name, $request) {
return \'this-is-a-test\';
//return get_the_author_meta( \'display_name\', $object[\'author\'] );
}