Role-based WordPress redirection using login_url hook
P粉533898694
P粉533898694 2023-09-11 17:53:57
0
1
592

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粉533898694
P粉533898694

reply all (1)
P粉369196603

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; }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!