How do I access the body of a WP API request in a custom route?

Question

I have created a custom route in WP API (v2 beta 4) to set a site option. I’m using AngularJS to make the API call, and for some reason, I’m not able to access the data sent within the request. Here is what I have so far:

gvl.service('gvlOptionService', ['$http', function($http) {

    this.updateOption = function(option, value) {

        return $http({
          method  : 'POST',
          url     : wpAPIdata.gvlapi_base + 'options',
          data    : { "option" : option,
                      "value" : value
                    },
          headers : { 'Content-Type': 'application/x-www-form-urlencoded',
                      'X-WP-Nonce' : wpAPIdata.api_nonce
                    }  
         })

    }

}]);

This successfully sends the request and the data posted looks something like this:

{"option":"siteColor","value":"ff0000"}

The request successfully makes it to my custom route and to the callback that I have specified. Here is that callback function within the class:

public function update_option( WP_REST_Request $request ) {

    if(isset($request['option']) && $request['option'] == 'siteColor') {
        $request_prepared = $this->prepare_item_for_database($request);
        $color_updated = update_option('site_color', $request_prepared['value'], false);

        if($color_updated) {
            $response = $this->prepare_item_for_response('site_color');
            $response->set_status( 201 );
            $response->header('Location', rest_url('/gvl/v1/options'));
            return $response;
        } else {
            // ...
        }


    } else {
        return new WP_Error( 'cant_update_option', __( 'Cannot update option.' ), array( 'status' => 400 ) );
    }

}

The problem is that this always fails and returns the WP_Error because $request[‘option’] is null.

When I var_dump($request), I see the JSON string in the [‘body’] portion of the object, but it won’t let me access that when calling that portion of the array. I’ve also tried using the methods for retrieving parameters noted in the documentation (http://v2.wp-api.org/extending/adding/), but none of those seem to return the data either. Am I missing something really basic here?

0
Ryan Hale 3 years 2020-07-07T09:10:20-05:00 0 Answers 63 views 0

Leave an answer

Browse
Browse