0

I want to redirect every user, depending on its user role, who wants to access home page (its my welcome login page).

I don't want to redirect users just after they log in, but after they are logged in and if they maybe again access home page incidentally.

Thanks

1

2 Answers 2

0

Try something like this. Also read about wp_redirect() too.

function redirect_by_role(){
  if (is_user_logged_in()) {
    $user = wp_get_current_user();
    if (is_home()) {
      if ( in_array( 'author', (array) $user->roles ) ) {
         $redirect_url= '';
         wp_redirect($redirect_url, 301); exit;
      }
      elseif( in_array( '**another_role_here**', (array) $user->roles ) ) {
         $redirect_url= '';
         wp_redirect($redirect_url, 301); exit;
      }
    }

  } else { 
   // Do what you want

  }
}
// Add the action with maximum priority
add_action('init','redirect_by_role',0);
3
  • Thanks Sabbir, but it doesnt look like its working. I logged as such user and it wont redirect me when I access home page, even I changed user roles and redirection urls.
    – Vucko
    Aug 21, 2017 at 11:39
  • please try now again Aug 21, 2017 at 11:48
  • Thanks again Sabbir, but its still the same. Don't know whats going on.
    – Vucko
    Aug 21, 2017 at 12:10
0

Vucko, try to change init hook to wp this way:

function redirect_by_role(){
  if (is_user_logged_in()) {
    $user = wp_get_current_user();
    if (is_home()) {
      if ( in_array( 'author', (array) $user->roles ) ) {
         $redirect_url= '';
         wp_redirect($redirect_url, 301); exit;
      }
      elseif( in_array( '**another_role_here**', (array) $user->roles ) ) {
         $redirect_url= '';
         wp_redirect($redirect_url, 301); exit;
      }
    }

  } else { 
   // Do what you want

  }
}
// Add the action with maximum priority
add_action('wp','redirect_by_role');

is_home() function is not working on init hook. It start works after parse_query. You can see hooks priority here

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.