wordpress - 如何在 WordPress REST API 中修改自定义帖子类型响应?
问题描述
我正在创建一个名为case-studies
.
我需要更改一些内容,例如第一次获取缩略图而不是获取 ID 等。我似乎无法像通常那样找到添加过滤器的方法,我已经尝试过了,但是add_filter
似乎对此不起作用。
这是代码:
function casestudies_post_type() {
$args = array(
'public' => true,
'label' => __( 'Case Studies'),
'singular_name' => __( 'Case Study', 'Post Type Singular Name', 'wpheirarchy' ),
'supports' => array ( 'title', 'editor', 'custom-fields', 'page-attributes', 'thumbnail' ),
'menu_icon' => 'dashicons-portfolio',
'show_in_rest' => true,
// 'rewrite' => array('slug' => 'case-studies'),
);
register_post_type( 'case-studies', $args );
}
add_action( 'init', 'casestudies_post_type' );
```
How can I modify the response that I get back?
解决方案
我相信该register_rest_field
功能正是您正在寻找的。在rest_api_init
钩子里打电话。它允许您通过 REST API 返回自定义数据,请注意不要弄乱其他插件或您的 UI 可能依赖的现有字段。
add_action('rest_api_init', function () {
register_rest_field(
<your post type, 'case-studies'>,
<name you want the new data to appear under>, array(
'get_callback' => function (array $post_object) {
... do your logic here
return whatever you want to be shown in the REST API
})
);
});
推荐阅读
- webview - 编译 uwp-community-toolkit dll 问题
- python - 在python中查找三个重叠集中的增量
- java - 使用 Kafka Connect API 将对象从 REST API 插入到 Kafka
- python - 如何将张量视为图像?
- java - 防止类卸载,java
- android - 在 Android 中看不到带有 ArrayAdapter 的 Listview
- cmake - 创建ros包
- sql - 仅选择组的所有元素具有相同值的组
- javascript - Javascript手动复制到剪贴板并单击
- php - Laravel 5.5 中间件不起作用