Filter Hook since 4.4.0
rest_pre_dispatch
Short-circuits a REST API request before routing
Description
rest_pre_dispatch lets you intercept a REST API request before WordPress even matches it to a route — the earliest point to block or fake a response.
When it runs
The very first REST API filter to run, before the route is matched — earlier than any permission_callback or route callback.
Signature
apply_filters( 'rest_pre_dispatch', mixed $result, WP_REST_Server $server, WP_REST_Request $request );Parameters
$resultmixed — Response to replace the requested route with, null by default.$serverWP_REST_Server — The REST server instance.$requestWP_REST_Request — The current request.
Examples
Basic
add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) {
if ( str_starts_with( $request->get_route(), '/my-plugin/v1' ) && ! is_user_logged_in() ) {
return new WP_Error( 'forbidden', 'Login required', [ 'status' => 401 ] );
}
return $result;
}, 10, 3 );Block an entire route namespace for logged-out users, before any route-specific logic runs.
Real case
add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) {
if ( '/wp/v2/posts' === $request->get_route() ) {
$cached = get_transient( 'rest_posts_cache' );
if ( false !== $cached ) {
return rest_ensure_response( $cached );
}
}
return $result;
}, 10, 3 );Serve a cached response for a high-traffic read-only endpoint without hitting the database.
Common Use Cases
- Block REST API access globally or per-route before any processing
- Serve a cached response without running the real route logic
- Rate-limit or IP-block at the earliest possible point
- Mock or A/B test an endpoint's response
Common mistakes
- Returning null (the default) still lets the request through — only a non-null return value short-circuits it, so forgetting this makes the filter silently do nothing
Related hooks
FAQ
What's the difference between rest_pre_dispatch and a route's permission_callback?
permission_callback runs per-route after matching, for auth checks on that specific endpoint. rest_pre_dispatch runs before routing even happens and can intercept every request site-wide.
Source: wp-includes/rest-api/class-wp-rest-server.php