Home  >  Q&A  >  body text

Role-based WordPress redirection using login_url hook

I'm trying to use login_url It works for users who are not logged in. But it doesn't work for logged in users (it redirects them to the /access-denied/ page, which is weird) and I don't really know why.

global $current_user;
$current_user = wp_get_current_user();

function my_login_page( $login_url ) {
    $user = $current_user;
    $valid_roles = [ "administrator", "editor", "custom-role" ];
    $the_roles = array_intersect( $valid_roles, $user->roles );

    if ( empty( $the_roles ) ) {
        return ( "/access-denied/" );
    } else {
        return ( "/login/" );
    }
}
add_filter( "login_url", "my_login_page", 10 );

P粉533898694P粉533898694427 days ago712

reply all(1)I'll reply

  • P粉369196603

    P粉3691966032023-09-12 00:20:19

    It’s not too difficult:

    $user = $current_user;
    $valid_roles = [ 'administrator', 'editor', 'custom-role' ];
    $the_roles = array_intersect( $valid_roles, $user->roles );
    
    if ( empty( $the_roles ) ) {
        nocache_headers();
        wp_safe_redirect( '/access-denied/' ); 
        exit;
    }

    reply
    0
  • Cancelreply