2

I'm trying to define a new REST Api endpoint based on WP REST API (version 2) and have question relating to what arguments are available to the validate_callback and sanitize_callback. Is the Request object made available for these callbacks?

For example:

add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
        'args' => array(
            'id' => array(
                'validate_callback' => 'my_validation'
            ),
        ),
    ) );
} );

function my_validation (WP_REST_Request $request) {
   return is_numeric( $request['id'] );   // Is this acceptable???
}
2

A quick search through the WP-API source revealed where validate_callback is being used:

wp-api/lib/infrastructure/class-wp-rest-request.php

$valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );

In this case, $this is an instance of WP_Rest_Request - so there's one. Now, for sanitize_callback:

$this->params[ $type ][ $key ] = call_user_func( $attributes['args'][ $key ]['sanitize_callback'], $value, $this, $key );

Same file, there's the $this you're looking for. So yes, both should get an instance of WP_Rest_Request as their second argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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