简体   繁体   English

WP Rest API 自定义端点 - JSON 返回 NULL

[英]WP Rest API Custom endpoint - JSON returns NULL

I am trying to slim down the JSON returned when using the Rest API.我正在尝试减少使用 Rest API 时返回的 JSON。 I am able to get it to work using the "_embed" parameter in the query, but it returns a HUGE amount of data I don't need.我可以使用查询中的“_embed”参数使其工作,但它返回了我不需要的大量数据。 So, per WP best practices I want to set up a custom end point and in it's callback call a function to output the three items I need.因此,根据 WP 最佳实践,我想设置一个自定义端点,并在它的回调中调用一个函数来输出我需要的三个项目。 Seems simple, however it returns NULL for all nodes when I try.看起来很简单,但是当我尝试时它为所有节点返回 NULL。 In my functions.php file I have:在我的functions.php文件中,我有:

function get_all_posts( WP_REST_Request $request ) {
    return [
        'id'        => $data->data['id'],
        'title'     => $data->data['title']['rendered'],
        'link'      => $data->data['link'],
        'date'      => $data->data['date'], //not correct
        //similar calls to get thumbnail image and category
    ];
}

Then the route and call back for the custom endpoint然后是自定义端点的路由和回调

add_action( 'rest_api_init', function () {
    register_rest_route( 'mydata/v1', '/all', array(
        'methods' => 'GET',
        'callback' => 'get_all_posts',
    ) );
} );

when I use the url - https://somedomain.com/blog/wp-json/mydata/v1/all I get the following on page:当我使用 url - https://somedomain.com/blog/wp-json/mydata/v1/all我在页面上得到以下内容:

{
    "id": null,
    "title": null,
    "link": null
}

You can pass field arguments to the API Like so:您可以将字段参数传递给 API,如下所示:

[url]/wp-json/wp/v2/tags?fields=id,name 

Note this is example is /tags, you can use /categories etc, and still specify the fields.请注意,这是 /tags 的示例,您可以使用 /categories 等,并且仍然指定字段。 I recommend installing the JSONView chrome plugin so that the dump of your JSON is readable when you test the endpoint .我建议安装 JSONView chrome 插件,以便在测试端点时可以读取 JSON 的转储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM