Here’s why limiting login attempts is crucial and how you can do it:
1- Prevents Brute-Force Attacks: By setting a limit, you significantly reduce the chances of attackers guessing the correct login credentials.
2- Reduces Server Load: Failed login attempts consume server resources. Limiting them can help keep your site running smoothly.
3- Enhances Security: It’s a fundamental security measure that adds a layer of protection to your WordPress site.
Here’s a refined and flexible version of the code you can add to your functions.php theme file:
// Define constants for maximum login attempts and lockout duration (in seconds)
define( ‘MAX_LOGIN_ATTEMPTS’, 5 );
define( ‘LOCKOUT_DURATION’, 300 ); // 5 minutes
/**
* Store failed login attempts.
*/
function record_failed_login() {
$ip_address = $_SERVER[‘REMOTE_ADDR’];
$failed_attempts = get_transient( ‘failed_logins_’ . $ip_address );
if ( false === $failed_attempts ) {
$failed_attempts = 1;
} else {
$failed_attempts++;
}
set_transient( ‘failed_logins_’ . $ip_address, $failed_attempts, LOCKOUT_DURATION );
}
add_action( ‘wp_login_failed’, ‘record_failed_login’ );
/**
* Check if login attempts exceed the limit.
*/
function check_login_attempts( $user, $username, $password ) {
$ip_address = $_SERVER[‘REMOTE_ADDR’];
$failed_attempts = get_transient( ‘failed_logins_’ . $ip_address );
if ( $failed_attempts >= MAX_LOGIN_ATTEMPTS ) {
$lockout_message = sprintf(
__( ‘Too many failed login attempts. Please try again after %s minutes.’, ‘your-text-domain’ ),
round( LOCKOUT_DURATION / 60 )
);
return new WP_Error( ‘too_many_failed_attempts’, $lockout_message );
}
return $user;
}
add_filter( ‘authenticate’, ‘check_login_attempts’, 30, 3 );
/**
* Clear failed login attempts on successful login.
*/
function clear_failed_logins( $username ) {
$user = get_user_by( ‘login’, $username );
if ( $user ) {
$ip_address = $_SERVER[‘REMOTE_ADDR’];
delete_transient( ‘failed_logins_’ . $ip_address );
}
}
add_action( ‘wp_login’, ‘clear_failed_logins’ );
?>