skip to Main Content

I have created a page template that will be used to show a custom wordpress login form.

<?php 
/*
* Template Name: Login
*/

get_header();
if( !is_user_logged_in() ){
?>

html code 
<?php 
} else {
  $user = wp_get_current_user();
  if( current_user_can('edit_users') && in_array('customrole', $user->roles) ){
   wp_redirect( site_url('/role-page') );
   exit;
  }
  if( current_user_can('edit_users') && in_array('customrole1', $user->roles) ){
   wp_redirect( site_url('/role-page1') );
   exit;
  }
}
get_footer();
?>

I’ve noticed that if an user is logged in, the page will be loaded and is blank, the users will be not redirected to the desired location. How I can fix this problem and let the logged users be redirected based on their role?

2

Answers


  1. Use template_redirect

    add_action( 'template_redirect', function() {
    
    if ( is_user_logged_in()){
    
    $restricted = array( 250(login page id) ); // all your restricted pages
    
    if ( in_array( get_queried_object_id(), $restricted ) ) {
         wp_redirect( site_url( '/custom_page slug' ) ); 
         exit();
      }
     }
    });
    
    Login or Signup to reply.
  2. I think we can use wp_redirect before content is sent to the browser. You should use hooks for that.

    But you can try this for custom template:

    global $current_user;
    $role         = $current_user->roles;
    $current_role = implode( $role );
    if ( $current_role == 'customrole' ) {
        $url = site_url( '/role-page' );
        echo "<script>window.location.href = '$url';</script>";
        exit;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search