Search code examples
phpwordpresscomparisonoperators

How to compare usernames in WordPress?


I am trying to show a message based on user names in WordPress. The code I am using:

$current_user = wp_get_current_user();
if( 'user1' && 'user2' == $current_user->user_login ){
    echo "discount 20%";
}
else {
    echo "you could save 20% if you are a VIP customer";
}

If I use the above code with && operator discount 20% is shown only to user2

If I use the above code with || operator discount 20% is shown to all the users even if the user is not logged in.

Code with ||

$current_user = wp_get_current_user();
if( 'user1' || 'user2' == $current_user->user_login ){
   echo "discount 20%";
}
else {
   echo "you could save 20% if you are a VIP customer";
}

I will be adding usernames continuously in time. discount 20% should be displayed only the usernames I will be adding. It should not displayed to other or guest/non-logged in users.

What I am doing wrong here?


Solution

  • If you are adding usernames in future, the following code will be useful.

    // List of VIP usernames.
    $vip_usernames = array(
        'user1',
        'user2'
    );
    
    $current_user = wp_get_current_user();
    
    // Check if the username is in VIP usernames array.
    if ( in_array( $current_user->user_login, $vip_usernames, true ) ) {
        echo "discount 20%";
    
    } else {
        echo "you could save 20% if you are a VIP customer";
    }