Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 894
bassment Avatar asked May 25 '17 21:05

bassment


1 Answers

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

like image 94
Igor Simic Avatar answered Oct 21 '22 18:10

Igor Simic