skip to Main Content

I’m currently looking for a way to add additional data to a WordPress REST request directly when it reaches WordPress so that I can access the data "later" in each REST route callback.

I’ve tried to set it in the rest_pre_dispatch filter but it seems to be not correct:

add_filter( 'rest_pre_dispatch', [ $this, 'filter_rest_pre_dispatch' ], 10, 3 );
public function filter_rest_pre_dispatch( $result, WP_REST_Server $server, WP_REST_Request $request ) {
    $request->set_attributes( [
        'test' => '1'
    ] );

    return $result;
}

Has anyone done this before and might help me out?

2

Answers


  1. Chosen as BEST ANSWER

    I've still found no solution for this. Instead I've created an abstract class which extends every class to register an endpoint and its function. In this abstract class I'm doing this for example to get a consumer key:

    /**
     * Returns the consumer key from the current request
     *
     * @return string
     */
    protected function get_request_consumer_key(): string {
        $consumer_key = '';
    
        if ( ! empty( $_GET['consumer_key'] ) ) {
            $consumer_key = sanitize_text_field( wp_unslash( $_GET['consumer_key'] ) );
        }
    
        if ( empty( $consumer_key ) && ! empty( $_SERVER['PHP_AUTH_USER'] ) ) {
            $consumer_key = sanitize_text_field( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) );
        }
    
        return consumer_key;
    }
    

    Thats the only solution in my case.


  2. You could try filter such as rest_request_after_callbacks or rest_request_before_callbacks and methods of the request object like $request->get_attributes() and $request->set_attributes() to change the REST endpoint arguments

    Also $request->set_body_params() would allow you to manipulate and add additional data to the request

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search