I am trying to restrict a page for all user roles except "librarian"
I've got a library dashboard on example.com/library-dashboard
When a loogged in user role that is not 'librarian' visits this page, I need to redirect them to example.com/subscription-needed
I am using the following function for this:
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;
}
}
My issue is that this function now redirects all pages to example.com/subscription-needed/
including the homepage and I am getting too many redirects error.
How can I fix this, so the function only works for the given user role librarian
on the page example.com/library-dashboard
?
So what I'm trying to achieve is that if librarian
& administrator
visits example.com/library-dashboard
then nothing happens and the page shows as normal.
But If any other user role that is NOT librarian
& administrator
visits the page example.com/library-dashboard
, they should be redirected to example.com/subscription-needed/
Check with below code.
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;
}
}
This worked for me, which you can use in place of both the is_corr_user()
and wpse69369_is_correct_user()
functions:
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.