Limit Login Attempts in WordPress with PHP

Problem/Use Case:

Protect your site from brute-force attacks by limiting login attempts.

Snippet:

// Limit login attempts
function check_login_attempts($user, $username, $password) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempts = get_transient($ip . '_attempts') ?: 0;

    if ($attempts >= 3) {
        return new WP_Error('too_many_attempts', 'Too many login attempts. Try again in 10 minutes.');
    }

    if (is_wp_error($user)) {
        set_transient($ip . '_attempts', $attempts + 1, 10 * MINUTE_IN_SECONDS);
    }

    return $user;
}
add_filter('authenticate', 'check_login_attempts', 30, 3);

Explanation:

Blocks login after 3 failed attempts for 10 minutes.

Where to Place It:

In functions.php.

Bonus Tip:

For advanced control, use plugins like Limit Login Attempts Reloaded.

Ndifon Luke
Ndifon Luke

Ndifon Luke is the founder & owner of Uncle Luke Digitals—a web design, digital marketing freelancer based in Bamenda, Cameroon. He has over 6 years of expertise in digital marketing and is very passionate about working with clients in achieving their business objectives.