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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
|| 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' ) ) {
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0