How to reedirect after login in WordPress based on user Role

In many WordPress development projects, a common requirement is to redirect users after login based on their user role. This enhances user experience, organizes navigation flow, and allows for personalized interactions depending on the user’s role.

In this article, we’ll explain how to implement this with a clear PHP example, and discuss how to leverage this functionality when developing custom plugins or solutions.

 

What Is a User Role in WordPress?

A user role in WordPress defines the actions a person can perform on the site. Some of the most common roles are:

  • Administrator: full access to all features.
  • Editor: can publish and manage posts, including those of others.
  • Author: can publish and manage their own posts.
  • Subscriber: can only manage their profile.

 

Redirecting Based on User Role

You can redirect users after login by utilizing the login_redirectfilter. This hook allows you to intercept the default redirection and define your own.

Here’s a functional example:

<?php
function redirectAfterLoginByUserRole( $redirectTo, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        $userRole = $user->roles[0];

        switch ( $userRole ) {
            case 'administrator':
                return admin_url();
            case 'editor':
                return home_url( '/editor-dashboard/' );
            case 'author':
                return home_url( '/author-section/' );
            case 'subscriber':
                return home_url( '/my-account/' );
            default:
                return home_url();
        }
    }

    return $redirectTo;
}

add_filter( 'login_redirect', 'redirectAfterLoginByUserRole', 10, 3 );
  • admin_url()redirects to the WordPress dashboard.
  • home_url( '/editor-dashboard/' )allows you to define a custom URL based on each role.
  • We’re using camelCase for function and variable names, adhering to WordPress development best practices.

 

Real-World Use Cases

Some scenarios where this can be applied:

  • In WooCommerce online stores, you can redirect frequent buyers to a my account section.
  • In online academies, students can be redirected to the course dashboard.
  • In custom membership developments, each user type can have its own area.

 

Customizing the redirection after login based on the user role is a practical and powerful way to enhance your users’ experience in WordPress. Additionally, it’s a straightforward functionality to implement that you can include in your custom plugins or client developments.

Are you creating plugins and looking to monetize them? Check out how to join our affiliate program and earn 35% for each sale.

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x