I created a custom role called "Travel Agent" using add_role( 'travel_agent', 'Travel Agent', array( 'book_hotel' ) );
at my themes functions.php
However, I don't want this user to have access to the dashboard so I want to redirect him to "my-account" after log in.
I am using this code at wp-login.php/functions.php without any luck:
function redirect_agents() {
if ( current_user_can('book_hotel') ){
return '/my-account';
}
}
add_filter('login_redirect', 'redirect_agents');
How ever, I don't get redirected.. But if I use such code without the If at functions.php as this:
function redirect_agents() {
return '/my-account';
}
add_filter('login_redirect', 'redirect_agents');
It works but then all users get redirected to my account. Any help is greatly appreciated!
Why not use WordPress global $current_user.
if(in_array('travel_agent', $current_user->roles)) {
return '/my-account';
}
The login_redirect
filter accepts three parameters: redirect_to
(contains current redirect value), request
(the URL the user is coming from) and user
(the user that has logged in as a WP_User object).
You can use the user
parameter inside your function to determine whether to redirect or not:
add_filter( "login_redirect", "custom_login_redirect", 10, 3 );
function custom_login_redirect( $redirect_to, $request, $user )
{
if ( in_array( "role_name", $user -> roles ) )
{
return "/hello-world";
}
// Remember to return something just in case,
// as filters can possibly block execution if
// they do not return anything.
else
{
return $redirect_to;
}
}
You might also want to verify that the $user
is a proper WP_User object, to ensure correct execution.
You can try using the $current_user global variable, but it may or may not be defined when login_redirect
is executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.