WP REST-API create posts with custom fields generated by CPT
Asked Answered
N

1

5

I used the CPT to create a post type UserQuestion with a few fields, such as ip_data. I want to be able to create one of this posts through API. So I looked into WP REST API .

However, the API offers /v2/user_question:

{
    "title" : "test2",
    "slug": "user_question",
    "status": "publish",
    "post_type": "user_question",
    "meta": {
        "ip" : "1111",
        "question": "test question",
        "answer": "yes, the answer"
    }
}

The post is created, but it's not updating the customized fields data.

How should I make the request?

Notions answered 22/2, 2017 at 7:9 Comment(2)
nvm. I just figured that I used the ACF. So using ACF to Rest-API plugin works perfect!Notions
hey @Yang, were you able to create a post and set the custom fields with the API?Photometry
E
8
add_action("rest_insert_user_question", function (\WP_Post $post, $request, $creating) 
{
    $metas = $request->get_param("meta");
    if (is_array($metas)) {
        foreach ($metas as $name => $value) {
            //update_post_meta($post->ID, $name, $value);
            update_field($name, $value, $post->ID);
        }
    }
}, 10, 3);

In your functions.php (or in your plugin) add the above add_action and function. Change the 'user_question' in the add_action to match your post type, for example "rest_insert_portfolio" for a portfolio post type. Use update_field if you're using Advanced Custom Fields or update_post_meta if you're using regular custom fields.

Evzone answered 10/11, 2018 at 9:35 Comment(1)
Thanks a lot! As they say where I live, tu é brabo.Comet

© 2022 - 2024 — McMap. All rights reserved.