How to Redirect Based on User Roles or Capabilities in WordPress

Home » Snippets » How to Redirect Based on User Roles or Capabilities 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

In websites with multiple types of users, redirecting users to different pages upon login based on their specific roles or capabilities can improve user experience significantly. WordPress, with its user-friendly interface and extensive functionalities, allows you to employ this strategy efficiently. In this article, we’ll explore and guide you through the process of setting up redirects based on user roles or capabilities within WordPress, making it easier for your subscribers, contributors, authors, editors, or administrators to navigate through your site.

					function wpturbo_redirect_based_on_roles() {
    if ( current_user_can('subscriber')) {
        wp_redirect(home_url());
        exit();
    }
}
add_action( 'admin_init', 'wpturbo_redirect_based_on_roles' );
				

The function wpturbo_redirect_based_on_roles() is declared in the initial part of our code snippet. Inside that function, we’re checking the current user’s capabilities and performing an action based on what it returns.

The code block:

if ( current_user_can('subscriber')) {
    wp_redirect(home_url());
    exit();
}

The function current_user_can('subscriber') is part of WordPress’s user Role and Capability system. What it does is assess the role of the user currently logged in and returns true if the user has the abilities of a ‘subscriber’. The ‘subscriber’ is a predefined role in WordPress with specific capabilities.

If the user does have the ‘subscriber’ role, the wp_redirect(home_url()) function is run. wp_redirect() is a WordPress function that, as the name implies, performs a redirect to the URL provided as an argument.

In our case, we’ve used the home_url() function as the argument, which retrieves the URL of the current WordPress installation’s homepage. Hence, when a user with ‘subscriber’ role tries to access the admin area, they are redirected to homepage of the website.

The exit() following wp_redirect(home_url()) function is very crucial, as it prevents further page load, ideally immediately after the redirect has been triggered.

The final line of code ties our function wpturbo_redirect_based_on_roles() to the ‘admin_init’ action hook using the add_action() function. The ‘admin_init’ hook triggers before any other hook when a user accesses the admin area. This makes it a good hook to use for our redirect function because it ensures the redirection takes place before any other actions that could potentially interfere with it.

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