Ban IPs That Try Common Attack Usernames
Blocks an IP address from logging in for a day as soon as it tries a username like "admin" or "test" that does not exist on your site.
Opens WPIDE on
Code
// Usernames that only bots try (they must not exist on your site).
$wpide_trap_usernames = array( 'admin', 'administrator', 'root', 'test', 'user', 'demo', 'wordpress', 'wp' );
$wpide_trap_ban_time = DAY_IN_SECONDS;
$wpide_trap_key = function () {
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : 'unknown';
return 'wpide_trap_' . md5( $ip );
};
add_action( 'wp_login_failed', function ( $username ) use ( $wpide_trap_usernames, $wpide_trap_ban_time, $wpide_trap_key ) {
$username = strtolower( trim( (string) $username ) );
if ( in_array( $username, $wpide_trap_usernames, true ) && ! username_exists( $username ) ) {
set_transient( $wpide_trap_key(), 1, $wpide_trap_ban_time );
}
} );
add_filter( 'authenticate', function ( $user ) use ( $wpide_trap_key ) {
if ( get_transient( $wpide_trap_key() ) ) {
return new WP_Error( 'wpide_trap_banned', '<strong>Error:</strong> Login is temporarily blocked from your network.' );
}
return $user;
}, 1 );
Notes
Never list a username that a real person on your site uses.
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.