gpt4 book ai didi

wordpress - 无法使用 get_post() 通过 REST API 检索自定义帖子类型数据

转载 作者:行者123 更新时间:2023-12-02 22:52:59 24 4
gpt4 key购买 nike

我正在尝试通过 REST API 从自定义帖子类型的单个帖子中获取数据。使用 get_posts() 可以正常工作:

function single_project($data) {
$args = array(
'post_type' => 'project',
'posts_per_page'=> 1,
'p' => $data
);
return get_posts($args);
}

add_action('rest_api_init', function () {
register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'single_project',
'args' => [
'id'
]
));
});

但是在我的前端我得到一个数组,我必须从该数组的第一个也是唯一一个项目中获取数据,这不太好。

get_post() 听起来像是解决方案,但由于某种原因它不起作用:ID 没有通过 REST API 传递,我不明白为什么。

function single_project($data) {
return get_post($data);
}

add_action() { ... } 代码是相同的。

知道为什么它不起作用吗?

最佳答案

如果您检查文档 ( Adding Custom Endpoints | WordPress REST API ),您会注意到 $data 实际上是一个数组,因此您的代码无法执行您期望的操作,因为您传递了一个数组到 get_post()函数需要一个整数(帖子 ID)或一个 WP_Post 对象。

所以:

function single_project($data) {
$post_ID = $data['id'];
return get_post($post_ID);
}

add_action('rest_api_init', function () {
register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'single_project',
'args' => [
'id'
]
));
});

关于wordpress - 无法使用 get_post() 通过 REST API 检索自定义帖子类型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58236742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com