By clicking on the button, the data is transmitted by an Ajax to the endpoint POST request. The data is in the form of a json array. Those. [{data: 1} {type: 1}, {data: 2} {type: 2}]

In endpoint, this is the code:

public function api_save_callback( WP_REST_Request $request ) { if ( !isset( $request )) { $response = new WP_REST_Response( 'Where is params', 400 ); return $response; } echo (var_dump($request)); $response = new WP_REST_Response( 'Ok', 200 ); return $response; } 

How to access elements in code?

PS Here is a sample POST data

 [{"post-id":"1512709186613861455_196691920","post-url":"some_url","post-author":"testing","post-date":"Wed Sep 24 2064 17:47:09 GMT+1000","pic-url":"some_url","post-text":"Sea"},{"post-id":"1512696819280595861_196691920","post-url":"some_url","post-author":"testing","post-date":"Thu Feb 04 2112 17:52:34 GMT+1000","pic-url":"some_url","post-text":"#sea"}] 
  • And what does var_dump ($ request) output? - KAGG Design
  • There is a lot of data, everything is not included in the comment, but in body all the most interesting is what you need ["body": protected] => string (617) "[{" post-id ":" 1512709186613861455_196691920 "," post- url ":" some_url "," post-author ":" 123 "," post-date ":" Thu Sep 25 2064 10:59:09 GMT + 1000 "," pic-url ":" some_url "," post -text ":" Sea "}, {" post-id ":" 1512696819280595861_196691920 "," post-url ":" some_url "," post-author ":" 123 "," post-date ":" Fri Feb 05 2112 11:04:34 GMT + 1000 "," pic-url ":" some_url "," post-text ":" # sea "}]" - Supply
  • So take the body and run this line through json_decode () - KAGG Design
  • Please correct your answer with full commands. maybe someone will need in the future not to understand for a long time. - Supply
  • Yes, the point of SO is precisely to leave clear answers for those who are looking for something similar for themselves. Answer corrected. - KAGG Design

2 answers 2

Decoding json in WordPress is as follows:

 $array = json_decode( $request, true ); 

The second parameter is true if you need an associative array.

In the source code of the WP_REST_Request class (the wp-includes / rest-api / class-wp-rest-request.php file) there is a get_body () function. Judging by its code, it should return the query string:

 $body = $request->get_body(); 

Thus, the complete code for getting data looks like this:

 $body = $request->get_body(); $data_array = json_decode( $body, true ); 
  • $ params = $ request-> get_params (); - vardump ($ params) returns array (0) {} - Supply
 $data = json_decode( $request->get_body(), true ); 

Further elements can be accessed in a loop:

 foreach($data as $item){echo $item['some_index']};