Showing Current User Name in WordPress

We can show username of currently logged in user in WordPress by using wp_get_current_user()
By adding the below code you can show username of loggedin user

 
if ( is_user_logged_in() ){ //checks if a user is loggedin or not
    $user_data    = wp_get_current_user();
    $user_details = $user_data->data;
    $username     = $user_details->user_login;
    echo $username;
}

How to Show Details of Current User in WordPress

You can use the above function wp_get_current_user() or you can also use get_userdata(user_ID) passing user Id in this will return all the data of that user.
Below is a sample code to show how you can use it.

$ID   = get_current_user_id(); //this will return current user ID
$data = get_userdata($ID);

echo $data->first_name;
echo $data->last_name;
echo $data->display_name;
echo $data->user_email;

For displaying the same data at multiple places you can create small shortcodes which can be put anywhere in your site. To make shortcode add below code on your function.php file of active theme

 
add_shortcode('show_username', 'fn_show_username');

function fn_show_username(){
    if ( is_user_logged_in() ){
        $ID   = get_current_user_id(); //this will return current user ID
        $data = get_userdata($ID);
        $html = $data->first_name;
    }
    return($html);
}

Now our shortcode is ready and to use it anywhere on your site just use [show_username]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: