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.
Opens WPIDE on
Code
// 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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.