// Custom shortcode to display logged-in user's name
function display_logged_in_username() {
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
return 'Welcome, ' . esc_html($current_user->display_name) . '!';
} else {
return 'Welcome, Guest!';
}
}
add_shortcode('logged_in_username', 'display_logged_in_username');
This code checks if a user is logged in and then retrieves the display name of the current user. If no user is logged in, it will display a default greeting for guests.
Use the Shortcode in Content or Widgets: You can now use the [logged_in_username] shortcode in your WordPress pages, posts, or widgets to display the logged-in user's name. Simply insert the shortcode wherever you want the name to appear. For example:
This is a sample page. [logged_in_username]
You can customize the message or the HTML structure as needed. Save and Test: Save the changes to your functions.php file and visit your WordPress site to test the shortcode. When a user is logged in, it should display a personalized greeting with their name. Remember to be cautious when editing theme files, and always keep a backup before making changes. If you're not comfortable editing code directly, consider using a child theme to avoid losing your modifications during theme updates.
0 Comments