0

I'm trying to avoid that subscriber users had access to admin. I'm using the following code:

add_action( 'admin_init', 'lr_no_admin_u_access', 100 );
function lr_no_admin_u_access() {
  global $current_user;
  $user_roles = $current_user->roles;
  $user_role = array_shift($user_roles);
  $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : site_url();

  if($user_role !== 'editor' && $user_role !== 'administrator'){
    wp_logout();
    wp_safe_redirect($redirect);
    exit;
  }
}

When a user navigates to '/wp-admin', should be logged out and redirected to the home page. Instead, a white page full of notices and warnings appears. Examples of errors:

Notice: Undefined offset: 2 in /home/[site]/public_html/wp-admin/includes/plugin.php on line 1911

Warning: Cannot modify header information - headers already sent by (output started at /home/[site]/public_html/wp-admin/includes/plugin.php:1911) in /home/[site]/public_html/wp-includes/functions.php on line 6270

... And many more. and many more. Why? How to avoid?

3
  • Where is the code located? Have you tried asking how to log out users who aren't editors/administrators instead? Your warning is likely because you're both logging out and redirecting, either of which will send headers and both require that headers have not been sent
    – Tom J Nowell
    Oct 27, 2020 at 16:27
  • I'm using test users (created by me). What I want is exactly to logout users that aren't editors or admin IF they navigate to wp-admin, and then redirect them directly to the website home page. Oct 27, 2020 at 16:30
  • I tested only the logout (commented out wp_safe_redirect). Same issues. Oct 27, 2020 at 16:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.