How to Restrict WP Admin Access to Subscribers in WordPress

WPTurbo » Snippets » How to Restrict WP Admin Access to Subscribers in WordPress
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 running a WordPress site with multiple users, you may want to limit access to the WordPress dashboard for some roles like subscribers. While subscribers can already access certain areas of the site like commenting and updating their profiles, they don’t have full access to the dashboard. In this article, we’ll show you how to restrict WordPress admin access to subscribers, allowing them to only see what they need and nothing more.

					function WPTurbo_restrict_admin_access() {
    if ( ! current_user_can( 'edit_posts' ) ) {
        wp_redirect( home_url() );
        exit;
    }
}
add_action( 'admin_init', 'WPTurbo_restrict_admin_access' );
				

The code snippet is used to restrict WP admin access to users who have the "subscriber" role. This is achieved by checking if the current user has the capability to "edit_posts" (which is given to all users by default except subscribers) and redirecting them to the home page if they don’t have the capability.

The first part of the code defines a new function called WPTurbo_restrict_admin_access(). This function checks if the current user has the capability to "edit_posts". If the user does not have this capability, then the function executes the wp_redirect() function which redirects the user to the home page. The exit() function is used in conjunction with wp_redirect() to prevent any further code execution after the redirection.

if ( ! current_user_can( 'edit_posts' ) ) {
    wp_redirect( home_url() );
    exit;
}

current_user_can() checks if the current user has a specific capability, in this case, "edit_posts". If the user doesn’t have the capability, then the wp_redirect() function is used to redirect the user to the home page (home_url()).

The last part of the code hooks WPTurbo_restrict_admin_access() function to the admin_init action. This action is fired before any other admin-related actions and is perfect for this use case. The function ensures that any user that is not allowed to "edit_posts" will not have access to the WordPress admin area.

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