如果登录用户尝试访问主页,是否根据用户角色重定向该用户?

时间:2017-08-21 作者:Vucko

我想重定向每个想要访问主页(我的欢迎登录页)的用户,具体取决于其用户角色。

我不想在用户登录后重定向他们,但在他们登录后,如果他们可能再次意外访问主页,我会重定向他们。

谢谢

2 个回复
SO网友:Sabbir Hasan

试试这样的。另请阅读wp_redirect()

function redirect_by_role(){
  if (is_user_logged_in()) {
    $user = wp_get_current_user();
    if (is_home()) {
      if ( in_array( \'author\', (array) $user->roles ) ) {
         $redirect_url= \'\';
         wp_redirect($redirect_url, 301); exit;
      }
      elseif( in_array( \'**another_role_here**\', (array) $user->roles ) ) {
         $redirect_url= \'\';
         wp_redirect($redirect_url, 301); exit;
      }
    }

  } else { 
   // Do what you want

  }
}
// Add the action with maximum priority
add_action(\'init\',\'redirect_by_role\',0);

SO网友:Anton Lukin

Vucko,尝试改变init 挂钩到wp 这样做:

function redirect_by_role(){
  if (is_user_logged_in()) {
    $user = wp_get_current_user();
    if (is_home()) {
      if ( in_array( \'author\', (array) $user->roles ) ) {
         $redirect_url= \'\';
         wp_redirect($redirect_url, 301); exit;
      }
      elseif( in_array( \'**another_role_here**\', (array) $user->roles ) ) {
         $redirect_url= \'\';
         wp_redirect($redirect_url, 301); exit;
      }
    }

  } else { 
   // Do what you want

  }
}
// Add the action with maximum priority
add_action(\'wp\',\'redirect_by_role\');
is_home() 函数不工作init 钩之后开始工作parse_query. 您可以看到挂钩优先级here

结束

相关推荐

在Functions.php中正确地将首页的CSS-TEMPLATE_REDIRECT排队?

我想加载一些特定的css来更改WP首页/主页的主体元素的颜色。在我的主题函数文件中,以下代码似乎有效,但有人能告诉我它是否“正确”吗?//Adding and Encuing styles for Front Page add_action( \'template_redirect\', \'front_page_design\' ); function front_page_design(){ if ( is_front_page() || is_home())