Assign a custom taxonomy to publish using the REST API

I use the built-in WP REST API to create messages (custom message type). This part works for me, below is an example of JSON that I send to create a new message.

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

The problem is how I also pass on which taxonomies to assign? It seems I can not find anyone who would ask or how to do this?

For context, it server 1creates entries and WP exists on server 2.

I also tried transmitting long metadata with a request, to which I can then iterate over on the WP server and set the taxonomy accordingly wp_set_post_terms () .

To do this, there is (almost) rest_insert _ {$ this-> post_type} , which is launched after creating one record or updated through the REST API.

The problem with this method is that the metadata is not set until AFTER the function finishes action_rest_insert_post_type(). This means that when I try to get the current metadata, it does not 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 confirmed that it $post->IDworks as expected, just that the metadata is not fully set ...

Please inform.

+4
source share
1 answer
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 used the post, but it should not be otherwise for custom post types, just change the action it enters. This works fine for me on a call 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 want to send this data via POST, you will need to change the way you receive the parameters

    $params = $request->get_body_params();

and send the data as:

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

+6
source

Source: https://habr.com/ru/post/1688399/


All Articles