Business photo created by senivpetro - www.freepik.com
Business photo created by senivpetro - www.freepik.com

Put WordPress in maintenance mode without any plugin

If for whatever reason you need to prevent your visitors from seeing a broken version of the site during maintenance, and to give them a heads up on the updates, WordPress has an embedded feature for handling maintenance mode that will automatically redirect all requests to a temporary maintenance page.

Simply create a .maintenance file in your website’s root directory and place the following code inside it:

$upgrading = time();
create .maintenance file

This will put WordPress in maintenance mode until you delete the .maintenance file.

To customize the message create a new file maintenance.php inside the wp-content folder:

create maintenance.php file

and inside it put whatever content that you want to serve to visitors while the website is in maintenance mode.

<html>
<head><title>Offline for maintenance</title></head>
 <body>
 <h2 style="text-align: center;">Sorry, we're currently offline for scheduled maintenance. 
We'll be back soon!</h2>
 <p style="text-align: center;"><img src="https://pcx3.com/wp-content/uploads/2021/01/stefan.png" width="600" height="400" /></p> 
 </body>
</html>

Now, how to enable access to registered users or Administrators only?

Okay, this is a 2 step process:

Step 1. Add the following code inside your WordPress theme funcitons.php file

add_action( 'wp_loaded', function() {
    global $pagenow;
    if(
        defined( 'IN_MAINTENANCE' )
        && IN_MAINTENANCE
        && $pagenow !== 'wp-login.php'
        && ! is_user_logged_in()
    ) {
        header( 'HTTP/1.1 Service Unavailable', true, 503 );
        header( 'Content-Type: text/html; charset=utf-8' );
        header( 'Retry-After: 3600' );
        if ( file_exists( WP_CONTENT_DIR . '/maintenance.php' ) ) {
            require_once( WP_CONTENT_DIR . '/maintenance.php' );
        }
        die();
    }
});

If you want to allow only users with specific capabilities, such as Administrators, use current_user_can('capability_to_allow') instead of is_user_logged_in(). See Codex for more info.

Step 2. Now to cause the maintenance mode put the following inside your wp-config.php file:

define('IN_MAINTENANCE', true);

After that, when you are ready to make your site public again, just remove this line or change true to false for easier re-enabling.

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.