The problem is that template_redirect
fires on every public page load. That means that after you redirect a user to a specific page, template_redirect
fires again, even if they’re already on the correct page. You just need to add a check to see if the current page they are on is same as where they should be.
function dashboard_redirect() {
global $current_user, $post;
//* Escape early if not on a 'dashboard' page
$current = trailingslashit( $_SERVER[ 'REQUEST_URI' ] );
if( false === stripos( $current, 'dashboard' ) ) {
return;
}
switch ( $current_user->membership_level->id ) {
case "2":
// Rookie Member level
$redirect="/rookie-dashboard/";
break;
case "3":
// Player Member level
$redirect="/player-dashboard/";
break;
//* Etc.
}
//* Redirect if we're not already on the right page
$current = trailingslashit( $_SERVER[ 'REQUEST_URI' ] );
if( $current !== $redirect ) {
wp_redirect( $redirect );
}
}
//* Conditionally add action when user tries to access a 'dashboard' page
$current = trailingslashit( $_SERVER[ 'REQUEST_URI' ] );
if( false !== stripos( $current, 'dashboard' ) ) {
add_action( 'template_redirect', 'dashboard_redirect' );
}
Added example code on how you can conditionally add the hook OR how to escape early from the callback if we’re not on a dashboard page. Use one or the other. I’d probably use the escape method, but only because it’s cleaner.