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

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]

Notes:

Wp Scriptly

This basic script, CSS style, and plugin are designed to function optimally assuming minimal interference from your theme or other plugins. If conflicts occur or further customization is needed, additional adjustments may be necessary. Please note that this script, CSS style, or plugin must be used AS IS.

Wp Scriptly

The WpScriptly Monthly newsletter offers top insights for WordPress pros: new scripts, plugins, resources, tips, tools, updates, and more every month.

Sidebar Subscribe

Comments: