繁体   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