# Allow Administrator Logins Only From Trusted IPs

> Administrators can only log in from the IP addresses or ranges you list; everyone else logs in as usual.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, login, ip
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/admin-login-ip-allowlist/

## Code

```php
// Trusted IPs. Single addresses or IPv4 ranges in CIDR form (203.0.113.0/24).
$wpide_admin_ips = array( '127.0.0.1', '203.0.113.0/24' );

$wpide_ip_in_list = function ( $ip, $list ) {
    foreach ( $list as $entry ) {
        if ( false === strpos( $entry, '/' ) ) {
            if ( $ip === $entry ) {
                return true;
            }
            continue;
        }

        list( $subnet, $bits ) = explode( '/', $entry, 2 );

        if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) && filter_var( $subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
            $mask = -1 << ( 32 - (int) $bits );
            if ( ( ip2long( $ip ) & $mask ) === ( ip2long( $subnet ) & $mask ) ) {
                return true;
            }
        }
    }

    return false;
};

add_filter( 'authenticate', function ( $user ) use ( $wpide_admin_ips, $wpide_ip_in_list ) {
    if ( ! ( $user instanceof WP_User ) || ! user_can( $user, 'manage_options' ) ) {
        return $user;
    }

    $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) $_SERVER['REMOTE_ADDR'] : '';

    if ( $wpide_ip_in_list( $ip, $wpide_admin_ips ) ) {
        return $user;
    }

    return new WP_Error( 'wpide_admin_ip', '<strong>Error:</strong> Administrator logins are not allowed from this location.' );
}, 100 );
```

## Notes

Add your own IP before activating (behind a proxy or CDN that may be the proxy address), or you will lock yourself out.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Allow Administrator Logins Only From Trusted IPs" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
