# Rate-Limit the REST API for Visitors

> Limits how many REST API requests a logged-out visitor can make per minute and answers "429 Too Many Requests" beyond that, slowing scrapers and scanners.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, rest-api, rate-limit
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/rate-limit-rest-api-visitors/

## Code

```php
// Requests per minute per IP address for logged-out visitors.
$wpide_rest_limit = 120;

add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) use ( $wpide_rest_limit ) {
    if ( null !== $result || is_user_logged_in() || empty( $_SERVER['REMOTE_ADDR'] ) ) {
        return $result;
    }

    $key  = 'wpide_rest_' . md5( (string) $_SERVER['REMOTE_ADDR'] . '|' . floor( time() / 60 ) );
    $hits = (int) get_transient( $key ) + 1;
    set_transient( $key, $hits, 2 * MINUTE_IN_SECONDS );

    if ( $hits > $wpide_rest_limit ) {
        return new WP_Error( 'wpide_rate_limited', 'Too many requests. Please slow down.', array( 'status' => 429 ) );
    }

    return $result;
}, 10, 3 );
```

## Notes

Writes a short-lived transient per visitor per minute; use it with a persistent object cache on busy sites.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Rate-Limit the REST API for Visitors" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
