Halloween Sale 15% off Ends in See the plans
PHP

Block Bad Bots by User Agent

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

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.