Ash*_*own 4 php rest wordpress wp-api
我正在使用内置的WP REST API来创建帖子(自定义帖子类型).我已经完成了这部分工作,下面是我提交的一些JSON示例,用于创建新帖子.
{
"title": "The story of Dr Foo",
"content": "This is the story content",
"status":"publish",
"excerpt":"Dr Foo story"
}
Run Code Online (Sandbox Code Playgroud)
问题是,我如何传递分配的分类?我似乎无法找到任何人询问或如何做的痕迹?
对于上下文,server 1正在创建帖子和WP存在server 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()
}
Run Code Online (Sandbox Code Playgroud)
我已经确认它$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);
Run Code Online (Sandbox Code Playgroud)
我已经使用了post,但这对于自定义帖子类型应该没有任何不同,只需更改它挂钩的动作即可.当用这样的东西调用时,这对我来说很好:
{
"title": "The story of Dr Foo",
"content": "This is the story content",
"status":"publish",
"excerpt":"Dr Foo story",
"terms": {
"mytaxonomy": [ "myterm", "anotherterm" ]
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想通过POST发送数据,你需要改变方式来获取params
$params = $request->get_body_params();
Run Code Online (Sandbox Code Playgroud)
并将数据发送至:
title=testtitle&content=testcotnent&status=publish&excerpt=testexcert&terms[mytaxonomy][]=myterm&terms[mytaxonomy][]=anotherterm