How to Restrict the WordPress Admin Panel to Administrators Only

WPTurbo » Snippets » How to Restrict the WordPress Admin Panel to Administrators Only
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

As a website owner, you may want to restrict access to the admin panel of your WordPress site to only administrators, in order to prevent unauthorized access and potential security breaches. Fortunately, WordPress offers several methods to achieve this goal. In this article, we’ll explore different ways to restrict access to the admin panel and ensure that only authorized users can access it.

					function wpturbo_restrict_admin_panel() {
    if ( ! current_user_can( 'administrator' ) && '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ) {
        wp_redirect( home_url() );
        exit;
    }
}
add_action( 'admin_init', 'wpturbo_restrict_admin_panel' );
				

In this tutorial, we will show you how to restrict the admin panel of your WordPress site to administrators only. This technique can be useful if you have multiple users with different roles and want to limit access to the admin panel.

The code snippet provided is a function named wpturbo_restrict_admin_panel() that checks if the current user is an administrator. If the current user is not an administrator, the user will be redirected to the homepage of the website.

The current_user_can() function with the administrator parameter is used to check if the current user has the administrator role. If the user does not have the administrator role, the rest of the function is executed.

The wp_redirect() function is then used to redirect the non-admin users to the homepage of the website. This function requires the URL of the page where you want to redirect the user. In this case, home_url() is used to get the URL of the homepage.

Finally, the exit function is called to prevent any further execution of code.

This function is then hooked to the admin_init action, which is executed whenever a user accesses the admin panel. By using this action, the function is executed at the earliest possible time after the user has requested the admin panel, before any other code or data is loaded.

In conclusion, this code snippet provides an effective solution to restrict the access of non-administrator users to the WordPress admin panel. By using the current_user_can() function to check the user role and the wp_redirect() function to redirect non-admin users, this function ensures that only authorized users can access the admin panel of your WordPress site.

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