How to redirect a user with specific “ROLE” to a specific page after login in WordPress

I have created a new user role named student_role I want to redirect the user with this role to form page(which I created from wp front end) when he logs in.

I tried peter login redirect plugin but failed.

Related posts

Leave a Reply

1 comment

  1. Try this :

    function rohil_login_redirect_based_on_roles($user_login, $user) {
    
        if( in_array( 'student_role',$user->roles ) ){
            exit( wp_redirect('Your page link goes here' ) );
        }   
    }
    
    add_action( 'wp_login', 'rohil_login_redirect_based_on_roles', 10, 2);
    

    Explanation

    If you look at the codex, you will find that wp_login provides two parameter: 1) $user_login which will return a string and 2) $user will return an object containing all the details.

    But you need to make sure that you also pass priority to that parameters otherwise It will give you an error.

    If you want to see what data are into that parameter, you can run below code for learning purpose only.

    function rohil_login_redirect_based_on_roles($user_login, $user) {
    
        var_dump($user); // Will give you an object
        var_dump($user_login); //Will give you a string
        die();
    
    }
    add_action( 'wp_login', 'rohil_login_redirect_based_on_roles', 10, 2);
    

    Make sure you delete above code from functions.php after checking what data it contains

    So as you can $user object contains roles which shows current logged in user’s role. So I simple checked that if($user->roles[0] === 'student_role') if current logged in user is having student_role then wp_redirect('Your page link goes here') redirect them to some page.

    Let me know if you have any doubt.