Wordpress redirect certain page to login page, but only for certain users

Viewed 40

My name is Lorenzo and I am making an (Wordpress) ecommerce site with an affiliate("/ambassador") section. There is only one problem. As soon as a not/ not signed in affiliate tries to access the affiliate dashboard. The user doesn't get redirected to the login page, but they will just see a blank page with only a header and a footer.

I would like to create code that would redirect not signed in users and users that don't have the administrator or the affiliate role, who are trying to access the affiliate dashboard, to the affiliate login section ("/ambassador-login/").

There is just one problem. I am a total noob at PHP. So I started doing my research, and after some copy and pasting I made this:

function wptips_has_user_role($check_role){
    $user = wp_get_current_user();
    if(in_array( $check_role, (array) $user->roles )){
        return true;
    }
    return false;
}

function custom_redirects() {
 
    if ( is_page('ambassador') && is_user_logged_in() ) {
        if(! wptips_has_user_role('Ambassdor') && ! wptips_has_user_role('Administrator') ) {
           wp_redirect( home_url( '/ambassador-login/' ) );
           die;
        }
    }
    if ( is_page('ambassador') && ! is_user_logged_in()){
        wp_redirect( home_url( '/ambassador-login/' ) );
        die;
        }

The code wont work. So now my question is if someone could help me with fixing the code and could maybe explain me what went wrong.

1 Answers
function wptips_has_user_role($check_role){
    $user = wp_get_current_user();
    if(in_array( $check_role, (array) $user->roles )){
        return true;
    }
    return false;
}

function custom_redirects() {
 
    if ( is_page('ambassador') && is_user_logged_in() ) {
        if(! wptips_has_user_role('affiliate') && ! wptips_has_user_role('administrator') ) {
           wp_redirect( home_url( '/ambassador-register/' ) );
           stop;
        }
    }
    if ( is_page('ambassador') && ! is_user_logged_in()){
        wp_redirect( home_url( '/ambassador-login/' ) );
        stop;
        }
    else {
        stop;
    }
 
}
add_action( 'template_redirect', 'custom_redirects' );

Fixed it myself, changed end to stop. This fixed different pages not loading and changed the roles first letter in a lowercase letten. So now as soon as a not signed-in user goes to the affiliate dashboard, he gets redirected to the login-page. As soon as a not affiliate or administrator tries to go to the affiliate dashboard, he gets redirected to the affiliate-register page.

Related