简体   繁体   中英

Wordpress REST API custom endpoint for method POST

I am currently working on a project which requires a WordPress website and a simple REST api. I discovered that WordPress has its own REST api and decided to extend its functionality to meet my needs. All I need to do is to have endpoints for GET and POST requests that retrieve/insert data from/to a table which is not directly related to WordPress (but in the same database). I successfully implemented all GET requests, however, I am struggling to get the POST ones working.
I have this route register defined:

register_rest_route('api/v1', 'create-player/', array(
        'methods' => 'POST',
        'callback' => 'create_player',
));

The client sends a request through ajax call which is expected to hit the endpoint from the route above. This is the ajax:

    $.ajax({
       method: "POST",
       url: '/wp-json/api/v1/create-player/',
       data : JSON.stringify(data),
       contentType: 'applcation/json',
       beforeSend: function (xhr){
           xhr.setRequestHeader("X-WP-None", locData.nonce);
           console.log('beforeSend');
       },
       success: function(response){
           console.log("success" + response);
       },
       fail: function (response){
           console.log("fail" + response);
       }
    });

I am not sure how to build the POST route register from the REST api, the other GET requests have an attribute args that map directly to the parameters passed in the endpoint. Do I need something like that to handle the request data when using POST? How do I get the data type passed from the ajax and then use it in my function create_player(); The WP REST API documentation seems to be incomplete and all of the information I found uses endpoints for built-in WordPress features such as posts/authors/blogs etc. but I don't need that, I just want to use the provided functionality and create my own interface. Thank you.

in your callback function you can use something like this:

 $param = $request->get_param( 'some_param' );

  // You can get the combined, merged set of parameters:
 $parameters = $request->get_params();

https://www.coditty.com/code/wordpress-api-custom-route-access-post-parameters

Finally found it! In order to access the body of the POST request use $request->get_body(); in your register_rest_route callback method.

Add POST in methods while registering route and in your callback function access your POST variables via $request array. That's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM