Displaying Logged-In Usersnames or Guests name on WordPress Pages and Posts

By Webmaster

Posted: 14m & 5d ago
2 min read

👁 Views: 2,270

(0) Leave a Comment

Shortcode - WpScriptly

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;
}
  1. Add the script to your functions.php file or use a code snippet plugin to include it.
  2. Add the CSS to youre styles.css or create a new CSS from the codesnippet plugin, add the .username to it.
  3. Insert the shortcode in any page or post content where you want the username/guest to appear.
[display_username]
Author: Webmaster

Hey, I’m Scot, the guy behind WpScriptly. I create simple, no-fluff WordPress plugins and tools to make your site easier to manage and more powerful. Everything I build is tested on my own projects first — if it’s here, it’s because it works. Thanks for checking out the site. Hope you find something useful at Wp Scriptly.

Follow me at:

Add your first comment to this post