Display logged-in user’s username on a WordPress site

This feature helps you to show a personalized message along with the username in the website’s header. For logged-in users, it can remind them that they are signed in. For guests, it encourages them to log in to access more features.

// Function to display the logged-in user's username in the header
function ts_add_username_to_header() {
    // Check if the user is logged in
    if ( is_user_logged_in() ) {
        // Get the current user's info
        $current_user = wp_get_current_user();
        // Output the welcome message with the username
        echo '<p class="welcome-message">Welcome, ' . esc_html( $current_user->user_login ) . '!</p>';
    } else {
        // Output the message for logged-out users
        echo '<p class="welcome-message">Welcome, Guest!</p>';
    }
}
add_action( 'wp_head', 'ts_add_username_to_header' );