Home > database >  Show default username
Show default username

Time:06-12

Hello. I use this code to show user's display name with a shortcode. When user is not logged in, it is empty, is there a way to show 'Visitor' or any other text when user is not logged in.

function display_current_user_display_name () {
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    return $user->display_name;
}
add_shortcode('current_user_display_name', 'display_current_user_display_name');

CodePudding user response:

You can check if the display is name is blank or null and returing the value by using php ternary operator:

return $display_name ? $display_name : "Visitor";

CodePudding user response:

Per the documentation, that function will return an WP_User object with the ID set to 0 is no one is logged in.

function display_current_user_display_name () {
    $user = wp_get_current_user();
    if($user->ID){
        return $user->display_name;
    }

    return "Visitor";
}
add_shortcode('current_user_display_name', 'display_current_user_display_name');
  • Related