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
Per the documentation, that function will return an
WP_User
object with the ID set to0
is no one is logged in.You can check if the display is name is blank or null and returing the value by using php ternary operator: