This snippet displays the username of the currently logged-in WordPress user using a shortcode. If the visitor is not logged in, it displays a login message instead.
<?php
function display_current_username() {
if ( ! is_user_logged_in() ) {
return '<p>Please log in to view your username.</p>';
}
$user = wp_get_current_user();
return '<p><strong>Username:</strong> ' . esc_html( $user->user_login ) . '</p>';
}
add_shortcode( 'current_username', 'display_current_username' );