Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.