Skip to content

Instantly share code, notes, and snippets.

@alanef
Last active July 19, 2022 22:54
Show Gist options
  • Select an option

  • Save alanef/654038791162c56a8c1c1318e5d8ec67 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/654038791162c56a8c1c1318e5d8ec67 to your computer and use it in GitHub Desktop.
add_filter( 'authenticate', function ( $user, $username, $password ) {
if ( ! $user->has_cap( 'manage_options' ) ) {
return $user;
}
$get_ip = function () {
$ipaddress = '0.0.0.0';
if ( getenv( 'HTTP_CF_CONNECTING_IP' ) ) {
$ipaddress = getenv( 'HTTP_CLIENT_IP' );
} elseif ( getenv( 'HTTP_CLIENT_IP' ) ) {
$ipaddress = getenv( 'HTTP_CLIENT_IP' );
} elseif ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) {
$ipaddress = getenv( 'HTTP_X_FORWARDED_FOR' );
} elseif ( getenv( 'HTTP_X_FORWARDED' ) ) {
$ipaddress = getenv( 'HTTP_X_FORWARDED' );
} elseif ( getenv( 'HTTP_FORWARDED_FOR' ) ) {
$ipaddress = getenv( 'HTTP_FORWARDED_FOR' );
} elseif ( getenv( 'HTTP_FORWARDED' ) ) {
$ipaddress = getenv( 'HTTP_FORWARDED' );
} elseif ( getenv( 'REMOTE_ADDR' ) ) {
$ipaddress = getenv( 'REMOTE_ADDR' );
}
// sanitize IP address
if ( false === \WP_Http::is_ip_address( $ipaddress ) ) {
$ipaddress = '0.0.0.0';
}
return $ipaddress;
};
// maybe modify for sub net / ranges etc
if ( ! in_array(
$get_ip(),
array(
'123.123.123.123',
'0.1.2.3',
'192.168.80.1',
)
) ) {
return new \WP_Error( 'not_valid_IP', '<strong>' . esc_html__( 'Error', 'your-text-domain' ) . '</srong>&nbsp;' . esc_html__( 'Your Error Message', 'your-text-domain' ) );
}
return $user;
},
40,
3
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment