如何在自定义路由中访问WP API请求的主体?


11

我已经在WP API(v2 beta 4)中创建了一个自定义路由来设置站点选项。我正在使用AngularJS进行API调用,由于某种原因,我无法访问请求中发送的数据。这是我到目前为止的内容:

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
                    }  
         })

    }

}]);

这成功发送了请求,发布的数据如下所示:

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

该请求成功进入了我的自定义路由和我指定的回调。这是该类中的回调函数:

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 ) );
    }

}

问题是,这总是失败并返回WP_Error,因为$ request ['option']为空。

当我var_dump($ request)时,我在对象的['body']部分看到了JSON字符串,但是当我调用数组的该部分时,它不允许我访问它。我还尝试使用方法来检索文档(http://v2.wp-api.org/extending/adding/)中指出的参数,但是这些方法似乎都不返回数据。我在这里真的缺少基本的东西吗?


有运气吗?
jgraup

Answers:


6

以前的答案是能够访问的数据的自定义端点使用

$parameters = $request->get_query_params(); 

检查查询参数 option

$parameters['option']

<?php
function my_awesome_func( WP_REST_Request $request ) {
    // You can access parameters via direct array access on the object:
    $param = $request['some_param'];

    // Or via the helper method:
    $param = $request->get_param( 'some_param' );

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

    // The individual sets of parameters are also available, if needed:
    $parameters = $request->get_url_params();
    $parameters = $request->get_query_params();
    $parameters = $request->get_body_params();
    $parameters = $request->get_default_params();

    // Uploads aren't merged in, but can be accessed separately:
    $parameters = $request->get_file_params();
}


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.