我正在使用内置的 WP REST API创建帖子(自定义帖子类型)。我已经让这部分工作了,下面是我提交的一些示例 JSON 以创建新帖子。
{
"title": "The story of Dr Foo",
"content": "This is the story content",
"status":"publish",
"excerpt":"Dr Foo story"
}
问题是,我如何同时传递要分配的分类法?我似乎找不到任何人询问或如何做的痕迹?
对于上下文,服务器 1
正在创建帖子,WP 存在于服务器 2
上。
我还尝试通过请求传递一个长元数据,然后我可以在 WP 服务器上循环并使用 wp_set_post_terms() 相应地设置分类法.
要做到这一点,有这个(几乎)rest_insert_{$this->post_type}在通过 REST API 创建或更新单个帖子后触发。
此方法的问题在于元数据直到 action_rest_insert_post_type()
函数完成后才设置。这意味着当我尝试检索当前的帖子元数据时,它不存在。
function action_rest_insert_post_type( $post, $request, $true ) {
$items = get_post_meta( $post->ID); // at this point in time, returns empty array.
//wp_set_terms()
}
我已经确认 $post->ID
正在按预期工作,只是元数据没有完全设置......
请指教。
最佳答案
function action_rest_insert_post( $post, $request, $true ) {
$params = $request->get_json_params();
if(array_key_exists("terms", $params)) {
foreach($params["terms"] as $taxonomy => $terms) {
wp_set_post_terms($post->ID, $terms, $taxonomy);
}
}
}
add_action("rest_insert_post", "action_rest_insert_post", 10, 3);
我使用过 post,但这对于自定义 post 类型应该没有任何不同,只需更改它 Hook 的操作即可。 当被这样调用时,这对我来说很好用:
{
"title": "The story of Dr Foo",
"content": "This is the story content",
"status":"publish",
"excerpt":"Dr Foo story",
"terms": {
"mytaxonomy": [ "myterm", "anotherterm" ]
}
}
如果您想通过 POST 发送该数据,则需要更改获取参数的方式
$params = $request->get_body_params();
并将数据发送为:
title=testtitle&content=testcotnent&status=publish&excerpt=testexcert&terms[mytaxonomy][]=myterm&terms[mytaxonomy][]=anotherterm
关于php - 分配自定义分类以使用 REST API 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015522/