Skip to content
Advertisement

Can I add data to an incoming REST request in WordPress?

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?

Advertisement

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement