Redirect WordPress Users After Login Based on Role - ProfilePress

Redirect WordPress Users After Login Based on Role

In this tutorial, I will be sharing a code snippet that will redirect users to a custom WordPress page based on their assigned role after they successfully log in to your site.

Note: the code below only works if they log in via a ProfilePress powered login form. And it should be pasted to your theme’s functions.php file or your site-specific / dummy plugin.

add_action( 'ppress_before_login_redirect', 'pp_redirect_by_role', 10, 3 );

function pp_redirect_by_role( $username, $password, $login_form_id ) {

	$a = get_user_by( 'login', $username );
	//retrieve the user roles
	$user_roles = $a->roles;

	/**
	 * we'll redirect users with a student role to https://xyz.com/student/
	 * and those with a teacher role to https://xyz.com/teacher/
	 */
	if ( in_array( 'student', $user_roles ) ) {
		$redirect = 'https://xyz.com/student/';
	}
	elseif ( in_array( 'teacher', $user_roles ) ) {
		$redirect = 'https://xyz.com/teacher/';
	}
	else {
		// default to login redirect url set in plugin settings
		$redirect = pp_login_redirect();
	}

	wp_redirect( $redirect );
	exit;
}

Code Explanation

What the code above does is, check the role of the user logging in. If the user is a student (i.e. has a “student” role), they get redirected to https://xyz.com/student/ and if a teacher (with “teacher” role), they are redirected to https://xyz.com/teacher/

To include more user role check and login redirection, create an additional `elseif` conditional block for them and include it in the above code.

Frightened by code? don’t worry, We got covered.

You can set the page or a custom URL users will be redirected after log-in under Redirection section of ProfilePress settings. See the screenshot below.

Note: URL entered in the custom URL field takes precedence over the selected page.

Using LoginWP

LoginWP is an excellent user redirection plugin from us for redirecting users to different URLs after they log in, log out and register based on different conditions.

To redirect users to different URLs after they login based on their user roles; firstly, install and activate the LoginWP plugin.

Go to LoginWP >> Redirections.

Click the Add New button.

Select “User Role” as the condition and the role we are creating a login redirect for.

You can optionally enter an order number. Say you have a rule for Subscriber with order 1 and Customer roles with order 2, and a user with both roles tries to log in. The rule with the lowest number (Subscriber with order 1) will be used.

Enter the URLs that users will be redirected to after they log in. You can also set the logout URL.

Note: You can use any of the available placeholders to form a URL or in place of a URL. Learn more about using placeholders here.

Finally, save the changes.

If you have any pre-sale questions, inquiring or contributions, please get in touch.