Bot Trap Link That Blocks Misbehaving Crawlers
Adds an invisible link that real visitors never see and well-behaved search engines are told to skip; any client that requests it anyway is blocked from the site for 24 hours.
Opens WPIDE on
Code
// Hours a trapped IP stays blocked.
$wpide_trap_hours = 24;
$wpide_trap_ip = function () {
return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
};
add_action( 'init', function () use ( $wpide_trap_ip, $wpide_trap_hours ) {
if ( is_admin() || is_user_logged_in() || ( defined( 'WP_CLI' ) && WP_CLI ) || wp_doing_cron() ) {
return;
}
$key = 'wpide_trap_' . md5( $wpide_trap_ip() );
if ( isset( $_GET['wpide-trap'] ) ) {
set_transient( $key, 1, $wpide_trap_hours * HOUR_IN_SECONDS );
}
if ( get_transient( $key ) ) {
status_header( 403 );
nocache_headers();
exit( 'Access denied.' );
}
}, 1 );
add_action( 'wp_footer', function () {
echo '<a href="' . esc_url( home_url( '/?wpide-trap=1' ) ) . '" rel="nofollow" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;"> </a>';
} );
add_filter( 'robots_txt', function ( $output ) {
return $output . "\nUser-agent: *\nDisallow: /?wpide-trap=\n";
} );
Notes
The trap URL is disallowed in robots.txt, so Google and Bing will not fall into it; logged-in users are never blocked.
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.