0

I'm implementing a callback for a GET Wp Rest request, which receives a WP_Rest_Request object.

function create_on_demand_post( \WP_REST_Request $request ) {
    $params = $request->get_json_params();
    // etc...
}

There are class methods which retrieve the request data, but I'm wondering if there's a way to access the data in this ArrayAccess implementation as I would with an array or object:

WP_REST_Request
    method:"POST"
    params:array(6)
    headers:array(8)
    body:"{"title": "From Python", "status": "publish", "content": "This is a post created using rest API", etc...}"
    route:"/my-plugin/v1/posts"
    attributes:array(7)
    parsed_json:true
    parsed_body:false

I have tried $request->body, which doesn't evaluate and $request['body'], as well as $request['body'][0], both of which return null.

Are you only able to access the attributes using the provided methods?

1
  • 3
    Those properties are protected, so unless you extend the class, you should just use the public method to get the property value, e.g. use $request->get_body() for the body property.
    – Sally CJ
    Commented Jan 27, 2022 at 4:34

1 Answer 1

0

As noted above in Sally CJ's comment, and as seen in the Wp Codebase, those are protected properties, so they are meant to be accessed only through the multiple get and set methods that the class exposes:

/**
  * Sets the header on request.
  *
  * @since 4.4.0
  *
  * @param string $key   Header name.
  * @param string $value Header value, or list of values.
  */
public function set_header( $key, $value ) {
    $key   = $this->canonicalize_header_name( $key );
    $value = (array) $value;

    $this->headers[ $key ] = $value;
}

// etc...

If you needed to access them directly, you would extend the class:

class MY_WP_REST_Request extends WP_REST_Request {

    public $params;
    // etc...
}

Though in my case, using the access methods provided is proving to be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.