[英]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
?
因此,我要实现的目标是,如果librarian
和administrator
访问example.com/library-dashboard
则什么也不会发生,并且该页面将正常显示。
但是,如果其他不是librarian
和administrator
用户角色访问了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.