On a recent membership project using Restrict Content Pro, it had been determined that all website users (front-end users, as well as administrators and editors) would log in from a page on the front end of the website. Users were then forwarded to their account page on the front end. However, where the user was a website administrator or editor they would have preferred to be sent to the website backend instead.
Luckily, Restrict Content Pro has a useful filter, rcp_login_redirect_url
, that I could leverage to make this happen. With some additional logic, it’s was possible to redirect users to different locations based on their user role.
<?php | |
add_filter( 'rcp_login_redirect_url', __NAMESPACE__ . '\\login_redirect', PHP_INT_MAX, 2 ); | |
/** | |
* @param string $redirect URL to redirect user to. | |
* @param object $user WP_User object | |
* | |
* @return mixed | |
*/ | |
function login_redirect( $redirect, $user ) { | |
$logged_in_user = get_userdata( $user->ID ); | |
if ( ! isset( $logged_in_user->roles ) || ! is_array( $logged_in_user->roles ) ) { | |
wp_die( 'You have no role assigned.' ); | |
} | |
$redirects = [ | |
/** | |
* If there is no explicit 'redirect_to' given, each role | |
* will fallback to the following ordered redirects upon | |
* logging in. | |
* | |
* role => redirect | |
*/ | |
'administrator' => admin_url(), | |
'subscriber' => home_url( 'members-area' ), | |
]; | |
// Fallback to user role default redirect. | |
foreach ( $redirects as $role => $redirect ) { | |
if ( in_array( $role, $logged_in_user->roles ) ) { | |
return $redirect; | |
} | |
} | |
// No fallback found for role, so proceed as normal. | |
return $redirect; | |
} |
Leave a Reply