skip to Main Content

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');

2

Answers


  1. 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');
    
    Login or Signup to reply.
  2. 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";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search