Displaying Logged-In Usersnames or Guests name on WordPress Pages and Posts
I wanted to display whether a visitor is a logged-in user or a guest within a WordPress page or post, allowing me to send them a personalized message. This can be achieved with a simple script that can be added to the functions.php
file or integrated using a code snippet plugin. By using this approach, you can create customized greetings or messages that enhance user engagement and provide a more personalized experience on your website.
The shortcode will automatically detect if the viewer is logged in or a guest, displaying a personalized greeting for logged-in users and a general welcome message for guests. This functionality helps to improve user interaction and makes your content more engaging and tailored to each visitor.
Live demo: https://wpscriptly.com/mission

I use fluent snippet plugin for all my functions, js, and CSS:
How to Use:
// Function to display logged-in username shortcode
function custom_username_display_shortcode() {
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
$nickname = $current_user->display_name;
return '<p class="username">Hello ' . '<span>' . esc_html($nickname) .',' . '</span>' . '</p>';
} else {
return '<p class="username">Hello <span>Guest,</span></p>';
}
}
add_shortcode('display_username', 'custom_username_display_shortcode');
CSS:
*Customize the css to match your website.
.username{
font-weight:bold;
color:#ff0000;
}
- Add the script to your
functions.php
file or use a code snippet plugin to include it. - Add the CSS to youre styles.css or create a new CSS from the codesnippet plugin, add the .username to it.
- Insert the shortcode in any page or post content where you want the username/guest to appear.
[display_username]
Was this information helpful?
Comments: