Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign custom taxonomy to post with REST API

I'm using the built-in WP REST API to create posts (custom post type). I've got this part working, below is some example JSON I submit to create a new post.

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

Problem is, how do I also pass which taxonomies to assign? I can't seem to find a trace of anyone asking or how to do it?

For context, server 1 is creating the posts and WP exists on server 2.

I have also tried passing a long meta data with the request, to which I can then loop over on the WP server and set the taxonomies accordingly with wp_set_post_terms().

To do that, there is this (almost) rest_insert_{$this->post_type} that fires after a single post is created or updated via the REST API.

The problem with this method is that the meta data is not set until AFTER the action_rest_insert_post_type() function has finished. This means that when I try to retrieve the current posts metadata, it doesn't exist.

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

}

I have confirmed that $post->ID is working as expected, it's just that the metadata isn't set fully...

Please advise.

like image 354
ProEvilz Avatar asked Oct 30 '17 12:10

ProEvilz


1 Answers

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

I've used post, but this shouldn't be any different for custom post types, just change the action it hooks into. This works fine for me when being called with something like this:

{
    "title": "The story of Dr Foo",
    "content": "This is the story content",
    "status":"publish",
    "excerpt":"Dr Foo story",
    "terms": {
        "mytaxonomy": [ "myterm", "anotherterm" ]
    }
}

If you wanted to send that data via POST, you'd need to change way to get the params to

    $params = $request->get_body_params();

and send the data as:

title=testtitle&content=testcotnent&status=publish&excerpt=testexcert&terms[mytaxonomy][]=myterm&terms[mytaxonomy][]=anotherterm

like image 158
janh Avatar answered Sep 20 '22 23:09

janh