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