Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.