# Block Bad Bots by User Agent

> Returns 403 Forbidden to aggressive SEO crawlers and scrapers that waste server resources, matched by their user agent.

- Type: PHP
- Runs: Frontend only
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, bots, performance
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/block-bad-bots/

## Code

```php
// Case-insensitive parts of user agent strings to block. AI crawlers are listed but commented out.
$wpide_blocked_bots = array(
    'MJ12bot', 'AhrefsBot', 'SemrushBot', 'DotBot', 'BLEXBot', 'PetalBot', 'MegaIndex', 'serpstatbot',
    'DataForSeoBot', 'ZoominfoBot', 'SeekportBot', 'Barkrowler', 'Bytespider',
    // 'GPTBot', 'ClaudeBot', 'CCBot', 'Google-Extended',
);

add_action( 'init', function () use ( $wpide_blocked_bots ) {
    $agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';

    if ( '' === $agent ) {
        return;
    }

    foreach ( $wpide_blocked_bots as $bot ) {
        if ( false !== stripos( $agent, $bot ) ) {
            status_header( 403 );
            header( 'Content-Type: text/plain; charset=utf-8' );
            exit( 'Forbidden' );
        }
    }
}, 0 );
```

## Notes

Only honest bots are stopped (others fake their user agent), and blocked SEO tools will no longer report on your site.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Block Bad Bots by User Agent" 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/
