How to Enable Maintenance Mode for the WordPress Admin Panel Only

WPTurbo » Snippets » How to Enable Maintenance Mode for the WordPress Admin Panel Only
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’re working on updates or changes to your WordPress site, you may want to put it into maintenance mode to avoid disruptions or errors for your visitors. However, sometimes you may need to access the admin area to continue making changes or updates. In this article, we’ll show you how to put your site into maintenance mode for visitors while still allowing access to the admin area for you and your team.

					function wpturbo_maintenance_mode() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 'Under Maintenance.' );
    }
}
add_action( 'admin_init', 'wpturbo_maintenance_mode' );
				

The purpose of this code snippet is to create a maintenance mode feature that is only visible to admin users in WordPress. This is useful when you need to perform maintenance work on your website, but you don’t want to take the website offline for your users. If you are a non-admin user, you will see the message "Under Maintenance" when you try to access any pages from the WordPress admin dashboard.

The wpturbo_maintenance_mode() function is defined to check if the current user has the capability to manage options using the current_user_can() function. If the user is not an admin, the function uses the wp_die() function to display the message "Under Maintenance" and terminate the script.

Here’s a line-by-line explanation of how the code works:

function wpturbo_maintenance_mode() {

This line is the function definition for the wpturbo_maintenance_mode() function. The function checks if the current user is an admin.

    if ( ! current_user_can( 'manage_options' ) ) {

This line checks if the current user does not have the capability to manage options. If this is true, it means that the user is not an admin.

        wp_die( 'Under Maintenance.' );

This line calls the wp_die() function to display the message "Under Maintenance" and terminates the script execution. This means that any further code after this line will not get executed.

}
add_action( 'admin_init', 'wpturbo_maintenance_mode' );

This line adds the wpturbo_maintenance_mode() function as an action to the admin_init hook. This hook is fired when a user tries to access any page in the WordPress admin dashboard. By adding this function as an action to this hook, we ensure that the function is only executed when a non-admin user attempts to access the admin dashboard.

Register an account to save your snippets or go Pro to get more features.