Menu
All schedule 18 min read

WordPress Login Security: Limiting Attempts Without Lockouts

Faraz Frank

Faraz Frank

December 4, 2026

WordPress Login Security

At 8:15 on a Monday, six people in the same office try to sign in to a client site. Four get in. The fifth mistypes a password twice. The sixth sees a red box: “Too many failed login attempts. Try again in 24 hours.”

The plugin counted by IP address. The office has one public IP. The requests that tripped the counter came from a botnet on another continent, but the person locked out sits twelve feet from the router.

That is the failure mode a login limit has to avoid. A control that stops bots by locking out the people who pay for the site is not security. It is a denial-of-service tool that the attacker gets to trigger for free.

This guide is about designing WordPress login security that slows guessing without turning a username into a weapon.

What a login limit is actually for

Three different attacks get lumped under “brute force,” and they need different responses.

Targeted guessing. An attacker picks one account and tries passwords: password, Summer2026!, the company name, the pet’s name from a public profile. The volume is low and the intent is specific. Per-account counters and a short backoff work here.

Credential stuffing. An attacker takes a list of email and password pairs from another breach and tries them across many accounts. Each account gets one or two attempts, so a per-account lockout never fires. The signal is the total failure rate and the number of distinct accounts from one source.

Password spraying. An attacker tries one common password against many usernames, then another. The volume is spread across accounts to stay under per-account thresholds. The signal is many usernames failing from a small set of IPs, or many IPs failing against a small set of usernames.

A login limit is not a substitute for any of the following:

  • A password manager and unique passwords.
  • Two-factor authentication or passkeys.
  • Patching WordPress, themes, and plugins.
  • Removing unused accounts and application passwords.
  • A web application firewall or server-level rate limit.

It is one layer. The goal is to make guessing expensive, keep legitimate users able to sign in, and leave a record that explains what happened. The security plugin guide covers the plugin options; this article focuses on the counting logic that determines whether those options help or hurt.

ControlSlowsDoes not stopCommon failure
Per-IP rate limitOne host trying many passwordsDistributed botnetsLocks out an office behind NAT
Per-username backoffTargeted guessingPassword sprayingAttacker locks out a known admin
CAPTCHASimple botsHuman click farmsAccessibility and privacy complaints
2FA or passkeyAccount takeover after a guessed passwordBrute force itselfUsers lose the second factor
WAF or fail2banRepeat offendersA patient, rotating attackerBans a shared IP or misses IPv6 rotation

The table is the reason a single plugin setting is not enough. Every control has a blind spot. The design has to combine them so the blind spots do not line up.

Why WordPress has no built-in limit

WordPress core authenticates users. It does not decide how many attempts are too many.

The hook is wp_login_failed, which fires inside wp_authenticate() after a failed attempt. It receives the username and a WP_Error object that describes the failure. The second argument was added in WordPress 5.4, so older snippets that only accept $username still work but lose the error detail.

Two details in core matter for anyone building a counter.

First, wp_login_failed is skipped for the empty_username and empty_password error codes. A bot that POSTs an empty password does not increment a plugin counter that listens to this hook. The request still reaches PHP, so server logs and edge rate limits see it, but a database-backed counter may not.

Second, XML-RPC calls wp_authenticate() too, so the same hook fires for XML-RPC failures. REST API requests using application passwords take a different path, with application_password_failed_authentication instead. If you only log wp_login_failed, you are not logging every door.

The authenticate filter is the other integration point. A plugin can return a WP_Error before the password handlers run, which is how most lockout plugins block an attempt. That is also how a plugin can lock out an administrator who is typing the correct password.

Core’s login form returns a generic error for a bad username or password. The login_errors filter can change the wording, but do not use it to reveal whether a username exists. Enumeration makes the attacker’s job easier and does not help the legitimate user.

The counting key is the whole design

Every login limit starts with a question: what are you counting?

Count by IP address

This is the default in most plugins, and it is the one that produces the Monday morning ticket.

An office, a university, a coworking space, and a mobile carrier can all put thousands of people behind one address. Carrier-grade NAT makes it worse: a phone on a mobile network may share an address with an entire neighborhood. A limit of five failures per hour per IP is generous for one person and absurd for a building.

IPv6 adds another wrinkle. A single device can rotate through addresses inside its own /64 prefix, so an attacker with IPv6 connectivity can present a new address for every attempt. Counting the full address is close to useless. Counting the /64 is the practical unit for IPv6, just as counting the exact address is the practical unit for IPv4.

Count by username

This stops targeted guessing and creates a denial-of-service primitive. If the attacker knows admin is the administrator, ten failed attempts can lock that account for a day. The attacker does not need to guess the password. They only need to keep the account closed.

Permanent or long username lockouts are the worst version of this. A short backoff is tolerable. A 24-hour lock on a known admin account is an invitation.

Count by username and IP

This is the usual compromise. It catches one host guessing one account and does not let a single attacker lock an account from elsewhere. It also misses the two attacks that matter most: a botnet spreading attempts across IPs, and a password spray that gives each account one attempt.

Count by network and by account separately

The design that holds up uses more than one counter:

  • Per account: a soft counter that triggers a CAPTCHA or a short backoff, never a permanent lock.
  • Per network: a hard counter that blocks repeat offenders at the edge, with a temporary ban.
  • Global: a failure-rate alert that catches a spray when no single key crosses its threshold.

The keys should be hashed if you store them for analytics, and raw if you need to hand them to a firewall. A SHA-256 hash of username|ip is enough for counting; it is not enough for a fail2ban ban, which needs the address.

KeyCatchesMissesMain risk
IP onlyOne host, many attemptsBotnets, IPv6 rotationNAT and CGNAT lockouts
Username onlyTargeted guessingSprayingAttacker locks out a known account
Username + IPOne host on one accountDistributed attacksRotating IPs
IP + subnetIPv6 rotation, small botnetsLarge distributed poolsCoarse blocks on shared hosting
Account + global rateSpraying, slow burnA single quiet attackerNeeds tuning and alerting

The practical rule: block on the network key, throttle on the account key, and alert on the global key. Do not use the account key as a ban.

Hard lockout versus backoff

A hard lockout is easy to explain: after five failures, the account is closed for an hour. It is also easy to abuse. The OWASP authentication guidance frames lockout as a tradeoff between guessing resistance and availability; the rest of this section is about keeping that tradeoff on the user’s side.

The alternative is backoff. The first failure is free. The second adds a short delay. The fifth requires a CAPTCHA. The tenth returns a 429 with a Retry-After header. The account is never permanently closed, and the attacker’s cost rises with every attempt.

A warning about sleep(): do not put a long sleep in the login handler. PHP-FPM has a fixed number of workers. An attacker who opens fifty login requests and makes each one sleep for five seconds can occupy the pool and take the site down without guessing a single password. A one-second delay is already expensive at scale. A 429 response is cheaper: it ends the request, frees the worker, and tells a well-behaved client to wait.

A minimal failure logger looks like this:

add_action( 'wp_login_failed', 'my_log_login_failure', 10, 2 );

function my_log_login_failure( $username, $error ) {
    global $wpdb;

    $wpdb->insert(
        $wpdb->prefix . 'login_failures',
        [
            'attempted_at' => current_time( 'mysql', true ),
            'username'     => mb_substr( sanitize_text_field( $username ), 0, 100 ),
            'ip'           => my_client_ip(),
            'user_agent'   => mb_substr(
                sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ?? '' ) ),
                0,
                255
            ),
            'error_code'   => $error->get_error_code(),
        ],
        [ '%s', '%s', '%s', '%s', '%s' ]
    );

    $key = 'login_fail_' . hash(
        'sha256',
        strtolower( $username ) . '|' . my_client_ip()
    );

    set_transient(
        $key,
        (int) get_transient( $key ) + 1,
        15 * MINUTE_IN_SECONDS
    );
}

function my_client_ip() {
    return isset( $_SERVER['REMOTE_ADDR'] )
        ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) )
        : '';
}

The table:

CREATE TABLE wp_login_failures (
    id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    attempted_at datetime NOT NULL,
    username varchar(100) NOT NULL,
    ip varchar(45) NOT NULL,
    user_agent varchar(255) NOT NULL DEFAULT '',
    error_code varchar(64) NOT NULL DEFAULT '',
    PRIMARY KEY  (id),
    KEY attempted_at (attempted_at),
    KEY ip (ip),
    KEY username (username)
) ENGINE=InnoDB;

varchar(45) holds an IPv6 address. The indexes are there because every query you actually run will filter by time, address, or username. Keep the retention window short: thirty to ninety days is enough for investigation and long enough to see a slow campaign.

If you want a PHP-side block as a last resort, keep it temporary and scoped:

add_filter( 'authenticate', 'my_check_login_backoff', 5, 3 );

function my_check_login_backoff( $user, $username, $password ) {
    if ( $user instanceof WP_User || empty( $username ) ) {
        return $user;
    }

    $key = 'login_fail_' . hash(
        'sha256',
        strtolower( $username ) . '|' . my_client_ip()
    );

    if ( (int) get_transient( $key ) >= 10 ) {
        return new WP_Error(
            'login_backoff',
            'Too many attempts from this network. Wait fifteen minutes and try again.'
        );
    }

    return $user;
}

This is a blunt instrument. It blocks the correct password too, which is the point of a lockout and the reason to keep the window short. The failure logger above sets the transient with a fifteen-minute expiry; clear it on a successful login for the same key.

A better use of the same counter is a CAPTCHA challenge rather than a hard block. The CAPTCHA protection guide covers the integration side. A CAPTCHA raises the cost for a bot and leaves a human a way through, provided the challenge is accessible and does not depend on a third-party script that privacy rules forbid.

The proxy header trap

Most login limits read $_SERVER['REMOTE_ADDR']. That is the address of the direct peer. On a server behind Cloudflare, a load balancer, or a reverse proxy, the direct peer is the proxy, not the visitor.

Plugins often “fix” this by reading X-Forwarded-For. That header is a comma-separated list, and the leftmost value is whatever the client sent. An attacker can set it to a new value on every request. If your counter trusts the leftmost value, the attacker never hits the limit. If it trusts the rightmost value without checking that the request came from your proxy, the attacker can still spoof it in some configurations.

The safe pattern is:

  1. Use REMOTE_ADDR by default.
  2. Trust X-Forwarded-For only when REMOTE_ADDR is one of your known proxy addresses.
  3. Read the address your proxy appended, not the one the client supplied.
  4. On Cloudflare, use CF-Connecting-IP only when the request originates from Cloudflare’s published IP ranges. Otherwise it is just another spoofable header.

WordPress core does not ship a trusted-proxy configuration. Some hosts configure it at the web server; some plugins guess. A quick test tells you which behavior you have:

curl -s -o /dev/null -w "%{http_code}\n" \
  -H "X-Forwarded-For: 203.0.113.10" \
  -d "log=admin&pwd=wrong" \
  https://example.com/wp-login.php

If your limit counts 203.0.113.10 as the client, the header is trusted. Send the same request with a different address and see whether the counter follows the header. If it does, the limit is bypassable by anyone who can set a request header.

Nginx’s real_ip module is the correct place to fix this at the server:

set_real_ip_from 10.0.0.0/8;
set_real_ip_from 172.16.0.0/12;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

Only list ranges you control. Listing 0.0.0.0/0 tells nginx to trust every client’s header, which is the same as having no limit at all.

Rate limit at the edge and the web server

The cheapest failed login is the one that never reaches PHP. Put a request-rate limit in front of wp-login.php and let the web server return 429 before WordPress boots. The web server security guide covers the layer below WordPress; this section is the part that touches the login endpoint.

Nginx’s request limiting module:

# http context
limit_req_zone $binary_remote_addr zone=wp_login:10m rate=5r/m;

server {
    # ...
    location = /wp-login.php {
        limit_req zone=wp_login burst=3 nodelay;
        limit_req_status 429;

        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Three notes on that config.

limit_req_zone belongs in the http block, not inside server. Placing it in the wrong context is the most common reason the config fails to load.

The zone counts requests, not failed logins. A normal login loads the form with a GET and submits with a POST, so a rate of five requests per minute with a burst of three is already tight for a person who reloads the page. Watch the 429 rate after deployment and tune it against real traffic.

$binary_remote_addr is the direct peer. Behind a proxy, combine this with the real_ip configuration above, or the zone will count every visitor as the proxy and block the whole site.

Cloudflare’s rate limiting rules can work at the edge if your plan includes them. A rule can match http.request.method eq "POST" and http.request.uri.path eq "/wp-login.php", count by IP, and challenge or block after a threshold. The request never reaches your origin, which is the point. Check the current plan limits before you promise a client a specific threshold.

For a self-managed server, fail2ban reads a log and adds a firewall rule. Do not build the filter from the nginx access log alone: a failed WordPress login usually returns 200 with the login form, and a successful login often returns 302. A filter that matches POST /wp-login.php will ban successful logins too.

Write a dedicated line from the failure handler instead:

error_log(
    sprintf(
        'WP_LOGIN_FAILED ip=%s user=%s',
        my_client_ip(),
        mb_substr( sanitize_text_field( $username ), 0, 100 )
    )
);

Then the filter:

[Definition]
failregex = WP_LOGIN_FAILED ip=<HOST>
ignoreregex =

And the jail:

[wordpress-login]
enabled  = true
filter   = wordpress-login
logpath  = /var/log/php-fpm/error.log
maxretry = 10
findtime = 10m
bantime  = 1h

The log path depends on your PHP-FPM configuration. If the line goes to wp-content/debug.log, point logpath there and make sure the file is not publicly readable. On a container without host firewall access, fail2ban may not be able to add the rule; use a Cloudflare-backed action or a WAF instead.

Whitelist the addresses you actually need: your office, your monitoring service, your support VPN. Do not whitelist a whole hosting provider or a /16 because one client sits there.

Protect the other doors

wp-login.php is the front door. It is not the only one. The admin area security guide covers the dashboard side; the sections below are the entry points that sit outside it.

XML-RPC

XML-RPC accepts a username and password and exposes methods such as wp.getUsersBlogs. It calls wp_authenticate(), so XML-RPC failures reach wp_login_failed, but the endpoint is also used for pingbacks and some mobile apps. If nothing on the site needs it, disable it:

add_filter( 'xmlrpc_enabled', '__return_false' );

If a client does need XML-RPC, give it an application password on a low-privilege user and rate-limit the endpoint at the server. Do not leave password authentication open on XML-RPC just because the login form has a limit.

REST API and application passwords

The REST API is not optional in modern WordPress. The block editor uses it. Application passwords authenticate API requests with a separate secret and bypass the login form, the passkey prompt, and most two-factor plugins.

That makes stale application passwords a quiet back door. Audit them:

wp user application-password list admin
wp user application-password delete admin <uuid>

If an integration only needs to read orders, give it a role or capability that can read orders and nothing else. A read-only integration with an administrator’s application password is a write-capable back door with a read-only job description.

Password reset and registration

The password reset form is another place to enumerate users. WordPress returns different messages for a valid and invalid email in some configurations. The lostpassword_errors filter can normalize the message, and a rate limit on lostpassword requests prevents an attacker from using the form as an email cannon.

Registration forms attract spam accounts. If registration is open, add a CAPTCHA or an email verification step, and review new users weekly. A spam account that never logs in still consumes a username and can be used for social engineering.

WooCommerce and membership forms

WooCommerce’s my-account and checkout login forms usually call wp_signon(), which means wp_login_failed fires and the hooks above see the attempt. Test your theme and any login customization, because a form that posts to a custom AJAX handler may skip the standard path. The same applies to membership plugins with their own login shortcodes.

Logging that helps after the fact

A login limit without a log tells you that something happened. It does not tell you what.

The table above captures the minimum: time, username, IP, user agent, and error code. Three queries turn it into something useful.

Top sources in the last hour:

SELECT ip,
       COUNT(*) AS failures,
       COUNT(DISTINCT username) AS accounts
FROM wp_login_failures
WHERE attempted_at > UTC_TIMESTAMP() - INTERVAL 1 HOUR
GROUP BY ip
HAVING accounts > 5
ORDER BY failures DESC
LIMIT 20;

Accounts under attack:

SELECT username,
       COUNT(*) AS failures,
       COUNT(DISTINCT ip) AS sources
FROM wp_login_failures
WHERE attempted_at > UTC_TIMESTAMP() - INTERVAL 1 HOUR
GROUP BY username
HAVING failures > 20
ORDER BY failures DESC
LIMIT 20;

A spike alert, throttled so it does not send a message per failure:

$count = (int) $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->prefix}login_failures
     WHERE attempted_at > UTC_TIMESTAMP() - INTERVAL 10 MINUTE"
);

if ( $count > 100 && false === get_transient( 'login_failure_alert' ) ) {
    set_transient( 'login_failure_alert', 1, HOUR_IN_SECONDS );

    wp_mail(
        get_option( 'admin_email' ),
        'Login failure spike',
        sprintf( '%d failed logins in ten minutes.', $count )
    );
}

The threshold is a starting point, not a universal number. A site with three administrators and no public registration should see almost no failures. A membership site with ten thousand customers will see a steady background of mistyped passwords. Measure a week of normal traffic before you set the alert.

Retention is a privacy decision. An IP address is personal data in the EU and the UK. Keep the log only as long as you need it, restrict access to it, and document the purpose. The cookie consent and analytics guide covers the consent side of analytics; a security log has a legitimate-interest basis in most cases, but “we keep it forever because it is useful” is not a retention policy.

Do not log the password. The WP_Error object does not contain it, but a custom handler that dumps the whole $_POST array will. Redact the request body before it reaches any log aggregator.

The recovery path

Every login control needs a way around it that does not depend on the control working.

A break-glass administrator account should have a strong unique password, a second factor stored offline, and no passkey requirement if passkeys are enforced elsewhere. It should not be the account an editor uses every day. It exists for the day the login plugin, the identity provider, or the network is broken.

If you are already locked out, the fix depends on what you can reach.

WP-CLI available:

wp user update admin --user_pass='new-strong-password'
wp user session destroy admin --all
wp config shuffle-salts

wp user session destroy --all revokes every session for the user. wp config shuffle-salts invalidates every authentication cookie on the site, which logs everyone out. Both are useful after a suspected compromise, and both are disruptive, so tell the client before you run them.

SSH or SFTP available, no WP-CLI: rename the offending plugin directory. WordPress deactivates a plugin whose main file is missing. This is crude, but it works when the login page is unusable.

Only database access available: remove the plugin’s entry from the serialized active_plugins option. Back up the row first. A malformed serialized value can break the plugin loader, and then you have two problems.

Only the host’s control panel available: use the host’s file manager to rename the plugin folder, or restore a backup from before the lockout. A backup restore is the last resort because it also rolls back content.

Test the recovery path on a staging copy before you need it. An untested break-glass procedure is a sentence in a document, not a control.

A rollout checklist

The numbers below are starting points. Tune them against a week of normal traffic, not against a blog post.

SignalStarting thresholdAction
Same IP, any username10 failures in 10 minutesReturn 429, temporary block
Same username, many IPs20 failures in 10 minutesCAPTCHA, alert the admin
One IP, many usernames10 distinct accounts in 10 minutesBlock the IP at the edge
Global failure rateThree times the weekly baselineAlert; investigate before blocking
Successful login after failuresAnyClear the per-key counter

The rollout order:

  1. Log first. Run the failure logger for a week. Find out how many failures are normal and which networks your team uses.
  2. Add the edge limit. Start with a generous request rate on /wp-login.php. Watch the 429 count.
  3. Add the account backoff. Trigger a CAPTCHA or a short delay, not a permanent lock.
  4. Add the alert. A daily summary is enough at first. Move to real-time when you know the baseline.
  5. Audit the side doors. Disable XML-RPC if unused, revoke stale application passwords, and review administrator accounts.
  6. Test the lockout. Try to lock yourself out on staging. Use a phone on a mobile network, a VPN, and an IPv6 connection.
  7. Document recovery. Write down the WP-CLI commands and the plugin-rename procedure. Store the document somewhere that does not require logging in to the site.

The test that matters most is the one most teams skip: after ten failed attempts, can a legitimate user still sign in with the correct password from the same network? If the answer is no, the control is a lockout, not a limit. The WordPress security guide covers the rest of the stack, from updates to file permissions, so the login limit is not the only control holding the site together.

FAQ

Does WordPress have built-in login attempt limiting?

No. WordPress core authenticates users and fires wp_login_failed, but it does not count attempts or block them. Login limiting comes from a plugin, the web server, a WAF, or a combination of the three.

How many failed attempts should trigger a lockout?

There is no universal number. A small site with no public registration can treat ten failures from one IP in ten minutes as hostile. A membership site with thousands of customers needs a higher threshold and a CAPTCHA instead of a hard block. Measure a week of normal traffic before choosing.

Why did I get locked out after only a few attempts?

The most common cause is an IP-based counter behind a shared office, campus, or mobile network. Another cause is a proxy header that reports the wrong client address, so every visitor appears to come from the same IP. Check the plugin’s counting key and the server’s trusted-proxy configuration.

Can an attacker lock out an administrator?

Yes. If the plugin locks by username, an attacker who knows the administrator’s username can keep the account closed with repeated failures. That is why a hard username lockout is a denial-of-service primitive. Use a short backoff, a CAPTCHA, and a break-glass account instead.

How do I clear a WordPress login lockout?

With WP-CLI, reset the password and destroy the sessions:

wp user update admin --user_pass='new-strong-password'
wp user session destroy admin --all

If the lockout comes from a plugin and you cannot reach WP-CLI, rename the plugin directory over SFTP or SSH. WordPress will deactivate it because the main plugin file is missing.

Does Cloudflare rate limiting work for WordPress login?

Yes, if your plan includes rate limiting rules and the rule matches POST requests to /wp-login.php. The request is blocked or challenged before it reaches the origin, which is cheaper than blocking inside PHP. Check the current plan limits and test the rule against a staging hostname first.

Does two-factor authentication stop brute force attacks?

No. Two-factor authentication protects the account after a password is guessed. The attacker can still generate failed logins and consume resources. It makes a successful guess less useful, but it does not replace a rate limit.

Will a login limit stop credential stuffing?

Only partially. Credential stuffing spreads one or two attempts across many accounts, so a per-account threshold never fires. You need a global failure-rate alert, an edge rate limit, and a check against breached-password lists. The OWASP credential stuffing guidance covers the detection side.

Should I rename the WordPress login URL?

It reduces automated noise, but it is not a security control. The login endpoint is still reachable by anyone who reads the site’s JavaScript or follows a password reset link. If you rename it, keep the rate limit and the failure log; do not treat the new URL as a secret.

What is the minimum viable WordPress login security setup?

A strong unique password for every administrator, two-factor authentication or passkeys, an edge rate limit on /wp-login.php, a failure log with an alert, XML-RPC disabled if unused, stale application passwords revoked, and a tested break-glass recovery procedure. A plugin can supply several of those, but not the recovery procedure.

Share: tw in
Faraz Frank

About Faraz Frank

Author at WP Frank. Writing about WordPress development, design, and best practices.

View all posts by Faraz Frank →