If you want to temporarily block access to your WordPress website (except for certain users), here’s a handy code snippet that can help you implement a maintenance mode. This allows you to redirect most visitors to a maintenance page while still allowing specific IP addresses to bypass the restriction.
/* Maintenance mode */
function redirect_users_to_maintenance_page() {
$allowed_ips = array("111.1.11.211", "22.22.22.10", "33.53.339.73");
$user_ip = $_SERVER['REMOTE_ADDR'];
if (!in_array($user_ip, $allowed_ips) && !is_page('maintenance')) {
$maintenance_page_url = home_url('/maintenance');
wp_redirect($maintenance_page_url);
exit;
}
}
add_action('template_redirect', 'redirect_users_to_maintenance_page');
How It Works:
Let’s break down what this code does, step by step:
-
Function Definition
The functionredirect_users_to_maintenance_page()
is created to handle the redirection logic. It is hooked into WordPress using thetemplate_redirect
action, which runs before a page template is loaded. -
Allowed IP Addresses
Inside the function, an array named$allowed_ips
is created. It contains the IP addresses of users who can still access the site during maintenance mode. You can customize this list by adding or removing IPs to suit your needs. -
User’s IP Address
The visitor’s IP address is stored in the$user_ip
variable, using the$_SERVER['REMOTE_ADDR']
superglobal to capture it. -
Condition Check
The code checks two things with anif
statement:- Is the user’s IP address not in the allowed list?
- Is the user not already on the maintenance page?
-
Redirect to Maintenance Page
If the conditions are met, the user will be redirected to the maintenance page. The$maintenance_page_url
variable is set to the URL of this page using thehome_url('/maintenance')
function. Make sure to replace/maintenance
with the actual slug of your maintenance page. -
Stop Further Code Execution
After the redirection,exit;
is called to ensure that no further code is processed.
How to Use It:
You can add this snippet to your theme’s functions.php
file or include it in a custom plugin. Don’t forget to:
- Update the
$allowed_ips
array with the IP addresses of the users who should bypass maintenance mode. - Ensure the
/maintenance
URL matches the actual URL of your maintenance page.
Why This is Useful:
This code is perfect if you need to restrict access to your site temporarily for updates, maintenance, or troubleshooting, while still allowing certain users (like admins or developers) to continue working.