Limiting access to the WordPress admin area by IP address can be useful when you want to restrict access to certain users or locations. Here’s how you can limit access to the WordPress admin area by IP address:
function wpsnippets_restrict_admin_by_ip() {
// Get the user's IP address.
$ip_address = $_SERVER[ 'REMOTE_ADDR' ];
// Define the IP addresses you want to allow.
$allowed_ips = array( '192.0.2.1', '203.0.113.0/24' );
// Return if the user's IP address is found in $allowed_ips
if ( in_array( $ip_address, $allowed_ips ) ) {
return;
}
// If the user's IP address is not in $allowed_ips or in the allowed range, redirect them to the home page.
wp_safe_redirect( home_url() );
exit;
}
add_action('admin_init', 'wpsnippets_restrict_admin_by_ip');
This code restricts access to the WordPress admin area to users with specific IP addresses. You can modify the $allowed_ips
array to include your own IP address or the IP addresses you want to allow.
That’s it! Now, when someone tries to access the WordPress admin area from an IP address that is not in the $allowed_ips
array, they will be redirected to the home page.