Wordpress - 按用户角色限制页面 - URL重定向

时间:2018-03-27 01:24:16

标签: php wordpress function if-statement redirect

我正在尝试限制所有用户角色的页面,除了" librarian"

我在example.com/library-dashboard

上有一个图书馆信息中心

当一个不是“图书管理员”的用户角色陷入困境时访问此页面,我需要将其重定向到example.com/subscription-needed

我正在使用以下功能:

function is_corr_user($page_slug) {

  // User has to be logged in
  if(!is_user_logged_in())
    return false;

  // All user roles
  $roles = wp_get_current_user()->roles;

  // For each page check if user has required role
  switch($page_slug) {
    case "library-dashboard":
     return in_array('librarian, administrator', $roles);
    default:
      return false;
  }
}


// Hook to wordpress before load and check if correct user is on page
add_action( 'wp', 'wpse69369_is_correct_user' );
function wpse69369_is_correct_user()
{
    global $post;

    // Redirect to a custom page if wrong user
    if(!is_corr_user($post->post_name)) {
      wp_redirect( '/subscription-needed/' );
      exit;
    }     
}

我的问题是此功能现在将所有页面重定向到example.com/subscription-needed/,包括主页,我收到的重定向错误太多。

如何解决此问题,因此该功能仅适用于页面librarian上的给定用户角色example.com/library-dashboard

所以我想要实现的是librarian& administrator访问example.com/library-dashboard然后没有任何反应,页面显示正常。

但是,如果任何其他用户角色不是librarian& administrator访问了example.com/library-dashboard页面,应将其重定向到example.com/subscription-needed/

2 个答案:

答案 0 :(得分:1)

请查看以下代码。

add_action('wp', 'redirectUserOnrole');
function redirectUserOnrole() {
 //First i am checking user logged in or not
 if (is_user_logged_in()) {
    $user = wp_get_current_user();
    $role = (array) $user->roles;
    //checking for the user role you need to change the role only if you wish
    if ($role[0] != 'librarian' || $role[0] != 'administrator') {
        global $post;
        if ($post->post_name == 'library-dashboard') {
            wp_redirect('/subscription-needed/');
            exit;
        }
    }
 } else {
    return true;
 }
}

答案 1 :(得分:1)

这适用于我,您可以使用它代替is_corr_user()wpse69369_is_correct_user()函数:

add_action( 'template_redirect', 'librarian_dashboard_redirect' );
function librarian_dashboard_redirect() {
    if ( is_user_logged_in() && is_page( 'library-dashboard' ) ) {
        $user = wp_get_current_user();
        $valid_roles = [ 'administrator', 'librarian' ];

        $the_roles = array_intersect( $valid_roles, $user->roles );

        // The current user does not have any of the 'valid' roles.
        if ( empty( $the_roles ) ) {
            wp_redirect( home_url( '/subscription-needed/' ) );
            exit;
        }
    }
}