根据用户角色将已登录的用户从页面重定向到特定页面

时间:2020-03-31 作者:Paolo Montalto

我试图通过不同的插件来完成这个简单的任务,但由于不同的原因,我找不到合适的插件。

我有一个带有登录表单的登录页面。用户登录时,会重定向到特定页面(基于用户角色)。如果用户再次访问登录页面,登录表单将显示一条欢迎消息,其中包含仪表板、配置文件和注销链接(请参阅图片)。

enter image description here

由于我需要避免这种情况,并且需要登录用户根据其角色只访问特定页面,因此我希望将登录用户从登录页面重定向到特定页面。

保罗是一个扮演“苹果”角色的用户。他登录并被重定向到Apple页面。然后他浏览网站,并尝试访问登录页面。当他尝试时,他被重定向到苹果页面。这同样适用于Ron,他的角色是“香蕉”,所以当他试图访问登录页面时,他会重定向到香蕉页面。

我最大的问题是,每个插件在登录后都有助于重定向,这很容易管理。你知道有什么简单的方法可以做到这一点,或者有什么建议可以在哪里找到?

2 个回复
SO网友:cjbj

您可以使用admin_init 来完成这件事。当管理页面开始加载时,此挂钩将启动,您可以使用它来redirect 将用户转到其他页面。像这样:

add_action(\'admin_init\',\'wpse362882_redirect_login_page\');
function wpse362882_redirect_login_page () {
  global $pagenow;
  if ( ($pagenow == \'wp-login.php\') && is_user_logged_in() ) {
    .. do some stuff to determine $url to redirect user based on role ..
    wp_redirect($url);
    exit;
    }
  }

SO网友:butlerblog

这在某种程度上取决于用户登录的位置和方式,以及这些页面在上下文中是什么。如果登录在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();
          }
     }
}

相关推荐

WooCommerce-TEMPLATE_REDIRECT如果结账且订单已付款?

在我的WooCommerce商店中,我想在付款完成后重定向到自定义的“感谢页面”。我正在使用以下代码:add_action( \'template_redirect\', \'myfunction\' ); function myfunction( $order_id ) { $order = wc_get_order( $order_id ); // I assume this is where I go wrong. Probably this is empty?&#