首页 > 解决方案 > 如何在 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? 

标签: wordpresscustom-wordpress-pageswordpress-rest-api

解决方案


我相信该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
    })
  );
});

更多信息:https ://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#adding-custom-fields-to-api-responses


推荐阅读