簡體   English   中英

WordPress 如何僅允許訂閱者訪問頁面

[英]WordPress how to give access to a page only for subscribers

我正在嘗試僅針對我的訂閱者用戶角色授予特定頁面的訪問權限,如果其他具有訂閱者角色或非角色用戶的其他人想要訪問此頁面,則將他們重定向到自定義登錄頁面,我嘗試使用以下代碼段,但我認為它有問題,你能幫我解決這個問題嗎

示例:限制對特定頁面的訪問

add_action( 'template_redirect', function() {

    // Get global post
    global $post;

    // Prevent access to page with ID 1052
    $page_id = 1052;
    if ( is_page() && ( $post->post_parent == $page_id || is_page( $page_id ) ) ) {

        // Set redirect to true by default
        $redirect = true;

        // If logged in do not redirect
        // You can/should place additional checks here based on user roles or user meta
        if ( current_user_can( 'subscriber' ) || !is_user_logged_in()) {
            $redirect = false;
        }

        // Redirect people without access to login page
        if ( $redirect ) {
            wp_redirect( get_site_url().'/custom-url-login' ); exit;
        }


    }

} );

你可以像這樣重構你的代碼:

add_action( 'template_redirect', 'checking_current_user' );

function checking_current_user() 
{

  global $post;

  global $current_user;
  
  $page_id = 1052;

  if ( 
      ( $post->post_parent == $page_id || is_page( $page_id ) )
      &&  
      ( !in_array('subscriber', $current_user->roles) )
     ) 
  {
    wp_safe_redirect( site_url('/custom-url-login') );
    exit;
  }
  
}

這個答案已經過測試並且工作正常!

這不會做你所要求的嗎?

// If user role 'subscriber' & logged in do not redirect
    // You can/should place additional checks here based on user roles or user meta
    if ( current_user_can( 'subscriber' ) && is_user_logged_in()) {
        $redirect = false;
    }

首先,您必須檢查用戶是否登錄,如果用戶未登錄,則需要將用戶重定向到登錄頁面,登錄后您需要應用代碼代碼才能正常工作。

add_action( 'template_redirect', 'check_current_user' );
function check_current_user(){
 global $post, $current_user;
$page_id = 1052;
if ( is_page() && ( $post->post_parent == $page_id || is_page( $page_id ) ) ) {
   if ( is_user_logged_in() ) {
      /*==Now check user is subscriber==*/
      $current_user = wp_get_current_user();
      $role = $current_user->roles;
      $currentRole = $role[0];
      if($currentRole == "subscriber"){
         $redirect = false;
      }else{
         $redirect = true;
      }
  }else{
     wp_safe_redirect( site_url('/custom-url-login') );
  }
 }
}

暫無
暫無

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

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