Shortcode - WpScriptly

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;
}
  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

These scripts, CSS styles, and plugins are designed to work best with minimal interference from themes or other plugins. If conflicts arise, adjustments may be needed.
Please note that they must be used as is.”

Let me know if you’d like any further refinements!

Wp Scriptly

Was this information helpful?

Comments: