这在某种程度上取决于用户登录的位置和方式,以及这些页面在上下文中是什么。如果登录在wp登录上,则另一个答案是可以的。php。您没有指定,因此此答案将从登录是否为前端页面的角度来接近它。
您需要钩住一个动作,但适当的动作取决于上下文。如果需要了解正在访问的页面(指前端页面),请使用template_redirect 因为页面将可用于is_page() (如果使用早期操作,例如init).
您还需要正确地检查用户是否具有指定的角色(虽然我的意见是,您在这种情况下使用WP角色不正确,但这是一个很长的讨论时间)。简单地说,please DO NOT do this as current_user_can( \'apple\' );. 请记住,在WP中,用户可以分配多个角色,因此您不能if ( \'role\' == $user_role ) {....
下面是一个一般的例子:
add_action( \'template_redirect\', \'my_logged_in_redirect\' );
function my_logged_in_redirect() {
// If it\'s the login page AND the user is logged in.
if ( is_page( \'login\' ) && is_user_logged_in() ) {
// Get the user info.
$user_id = get_current_user_id();
$user = get_userdata( $user_id );
// Determine the redirect URL
$url = false;
if ( in_array( \'apple\', $user->roles ) ) {
$url = \'/apple/page/\';
}
if ( in_array( \'banana\', $user->roles ) ) {
$url = \'/banana/page/\';
}
// Redirect if a $url is set
if ( $url ) {
wp_safe_redirect( $url );
exit();
}
}
}