Limit Login Attempts

Implement a basic login attempt limit to protect against brute force attacks.

<?php
function limit_login_attempts($user, $username, $password) {
    $max_attempts = 5;
    $attempts = get_transient('login_attempts_' . $username);

    if ($attempts === false) {
        $attempts = 0;
    }

    if ($attempts >= $max_attempts) {
        wp_die('Too many login attempts. Please try again later.');
    }

    if (wp_authenticate($username, $password)) {
        delete_transient('login_attempts_' . $username);
        return $user;
    } else {
        $attempts++;
        set_transient('login_attempts_' . $username, $attempts, 15 * MINUTE_IN_SECONDS);
        return new WP_Error('invalid_credentials', __('Invalid username or password.'));
    }
}
add_filter('authenticate', 'limit_login_attempts', 30, 3);

Post Comment