rest_pre_dispatch
Allows you to override a REST API response before its standard processing.
If the filter returns a non-empty value, that value is used to create the REST request response. See $result.
Usage
add_filter( 'rest_pre_dispatch', 'wp_kama_rest_pre_dispatch_filter', 10, 3 );
/**
* Function for `rest_pre_dispatch` filter-hook.
*
* @param mixed $result Response to replace the requested version with. Can be anything a normal endpoint can return, or null to not hijack the request.
* @param WP_REST_Server $server Server instance.
* @param WP_REST_Request $request Request used to generate the response.
*
* @return mixed
*/
function wp_kama_rest_pre_dispatch_filter( $result, $server, $request ){
// filter...
return $result;
}
- $result(mixed)
The response that will replace the REST server's default response. Returning an empty value
false|null|0|''|[]does nothing and REST continues to work normally. The following objects can be returned:- WP_REST_Response
- WP_HTTP_Response
- WP_Error
- Empty —
false null 0 '' []
The returned value is passed through rest_ensure_response().
- $server(WP_REST_Server)
- The server instance.
- $request(WP_REST_Request)
- The current REST API request as a
WP_REST_Requestobject.
Examples
#1 Close all WordPress REST routes to public access
add_filter( 'rest_pre_dispatch', 'close_rest_api_routes', 10, 3 );
/**
* Close REST API routes from public access.
*
* @param WP_REST_Response|WP_Error|null $result
* @param WP_REST_Server $rest_server
* @param WP_REST_Request $request
*
* @return WP_REST_Response|WP_HTTP_Response|WP_Error|null
*/
function close_rest_api_routes( $result, $rest_server, $request ){
// maybe authentication error already set
if( ! is_null( $result ) )
return $result;
// only for `/wp/v2` namespace
if(
// only for `/wp/v2` namespace
'/wp/v2' === substr( $request->get_route(), 0, 6 )
// Administrator
&& ! current_user_can( 'manage_options' )
){
return new WP_Error( 'rest_not_logged_in', 'Your capability is low.', [ 'status' => 401 ] );
}
return $result;
}Changelog
| Since 4.4.0 | Introduced. |
Where the hook is called
rest_pre_dispatch
rest_pre_dispatch
wp-includes/rest-api/class-wp-rest-server.php 1079
$result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
wp-includes/rest-api/class-wp-rest-server.php 1866
$result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
Where the hook is used in WordPress
wp-includes/rest-api.php 256
add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );