是的,这绝对是可能的。您需要采取几个步骤来实现这一目标;
检查用户当前是否在首页,您可以使用is_front_page 函数,您可能需要使用is_home 或者两者都可以,具体取决于您的配置和要求检查用户当前是否已登录,您可以使用is_user_logged_in 函数检查它们是否正确获取用户角色。可以从返回的对象中检索这些wp_get_current_user检查用户是否具有预期角色重定向。您应该使用wp_safe_redirect 这将确保您重定向到的url是属于您的站点的url然后在init 钩子可以确保某些方法和数据可用,例如当前用户,并允许尽快进行重定向。
完整示例如下所示:
function redirect_from_front_page() {
$redirect_url = \'/example/url\'; // Change this to the path or url you wish to redirect to.
$expected_role = \'custom-role\'; // Change this to the role you would like to redirect based on.
/**
* Check that the user is on the front page
* before continuing.
*/
if( ! is_front_page() ) {
return;
}
/**
* Check that the user is logged in.
*/
if( ! is_user_logged_in() ) {
return;
}
/**
* Get the currect user roles.
*/
$user = wp_get_current_user();
$roles = $user->roles;
/**
* If the user has a role that matches the expected role
* redirect to the given page.
*/
if ( in_array( $expected_role, $roles ) ) {
wp_safe_redirect( $redirect_url );
exit;
}
}
add_action( \'init\', \'redirect_from_front_page\' );