Block Bad Bots by User Agent
Returns 403 Forbidden to aggressive SEO crawlers and scrapers that waste server resources, matched by their user agent.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.