php - WordPress 如何仅向订阅者授予对页面的访问权限

标签 php wordpress redirect woocommerce custom-wordpress-pages

我正在尝试仅为我的订阅者用户角色授予特定页面的访问权限,如果其他具有订阅者角色或非角色用户的人想要访问此页面,则将他们重定向到自定义登录页面,我尝试使用以下方法片段,但我认为它有问题,你能帮我解决这个问题

示例:限制对特定页面的访问

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

这个答案已经过测试并且工作正常!

关于php - WordPress 如何仅向订阅者授予对页面的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69801444/

相关文章:

Laravel 登录后重定向回原始目的地

java - 从 Path 中捕获元素

php - MySQL 中的 float 不正确

php - 将不同的输入值插入一列 (MySQL)

wordpress - Gravity Forms - 多站点的全局表单

php - 如何在使用更改或 keyup 后修复表单提交

php curl ssl 错误号 35

php - 根据 IP 地址国家代码重定向访客

wordpress - wp_enqueue_style不加载CSS

apache - 在 apache 中排除站点重定向到 https