分配自定义分类以使用REST API发布

时间:2017-10-30 12:39:16

标签: php wordpress rest wp-api

我使用内置WP REST API创建帖子(自定义帖子类型)。我已经完成了这部分工作,下面是我提交的一些JSON示例,用于创建新帖子。

{
 "title": "The story of Dr Foo",
 "content": "This is the story content",
 "status":"publish",
 "excerpt":"Dr Foo story"
}

问题是,我如何传递分配的分类?我似乎无法找到任何人询问或如何做的痕迹?

对于上下文,server 1正在创建帖子,WP存在于server 2

我还尝试使用请求传递长元数据,然后我可以在WP服务器上循环并使用wp_set_post_terms()相应地设置分类法。

要做到这一点,在通过REST API创建或更新单个帖子后会发出(几乎)rest_insert_{$this->post_type}

此方法的问题是,在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按预期工作,只是元数据未完全设置...

请指教。

1 个答案:

答案 0 :(得分:9)

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);

我已经使用了帖子,但这对于自定义帖子类型不应该有任何不同,只需更改它挂钩的操作即可。 当用这样的东西调用时,这对我来说很好:

{
    "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