簡體   English   中英

Wordpress-按用戶角色限制頁面-URL重定向

[英]Wordpress - Restrict page by user role - URL Redirect

我試圖限制除“圖書管理員”以外的所有用戶角色的頁面

我在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/包括主頁,並且我收到太多重定向錯誤。

如何解決此問題,因此該功能僅適用於example.com/library-dashboard頁面上給定的用戶角色librarian

因此,我要實現的目標是,如果librarianadministrator訪問example.com/library-dashboard則什么也不會發生,並且該頁面將正常顯示。

但是,如果其他不是librarianadministrator用戶角色訪問了example.com/library-dashboard頁面,則應將其重定向到example.com/subscription-needed/

檢查以下代碼。

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;
 }
}

這對我有用,可以用它代替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;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM