Question

I used the snippet below to lock out all administrators and editors except myself

if ( is_user_logged_in() ){
    $current_user = wp_get_current_user() ;
    if ( in_array( 'administrator', (array) $current_user->roles ) || in_array( 'editor', (array) $current_user->roles )) {
        if ($current_user->user_login != 'sheila' ){
            wp_logout();
            return new WP_Error( 'login_again_please', 'Please log in again' );
        }
    }
}

When I try to add a second user in the second if statement we are both locked out:

if ( is_user_logged_in() ){
    $current_user = wp_get_current_user() ;
    if ( in_array( 'administrator', (array) $current_user->roles ) || in_array( 'editor', (array) $current_user->roles )) {
        if (($current_user->user_login != 'john' ) || ($current_user->user_login != 'sheila' )){
            wp_logout();
            return new WP_Error( 'login_again_please', 'Please log in again' );
        }
    }
}

How do I fix the above snippet to allow two administrators/editors with specific usernames to login or can I have an alternative with the same outcome?

Was it helpful?

Solution

|| means OR. Your code will never allow $current_user to proceed because one of the OR conditions will fail. Try using AND && instead:

if ( ($current_user->user_login != 'john') && ($current_user->user_login != 'sheila' ) ) {

OTHER TIPS

Looks like it would work! I ended up using something like this:

if( !($some_variable === 'uk' || $another_variable === 'in')){ 
    //this occurs when neither of the above are true
}

courtesy of a comment by @Habchi on this thread: https://stackoverflow.com/questions/19949923/simpler-way-to-check-if-variable-is-not-equal-to-multiple-string-values I'll post the full solution later if someone doesn't beat me to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top