php – How to work with POST data at the endpoint?

Question:

When the button is clicked, the data is sent by Ajax to the endpoint POST request. Data as json array. Those. [{data: 1} {type: 1}, {data: 2} {type: 2}]

In the 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 do you refer to elements in your 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"}]

Answer:

Json decoding in WordPress is done like this:

$array = json_decode( $request, true );

The second parameter is true if an associative array is needed.

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

$body = $request->get_body();

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

$body = $request->get_body();
$data_array = json_decode( $body, true );
Scroll to Top