NewUser
NewUser

Reputation: 295

How to retrieve a username out of a user ID on WordPress using PHP

In my Multisite Installation i get the user id with:

$user_ID

and it works fine in my subsite (subdomain). My users can only log in from the mainsite and i didnt figure out how to get the username when the user is logged in and visits the subsite (subdomain) But the User ID works fine...

I need the name of the user? Any way to filter the name out of the user ID - so i get the name of the user instead of the user id number?

Thank you so much

Upvotes: 6

Views: 38875

Answers (1)

Shiva
Shiva

Reputation: 20935

Try the get_user_by(...) function, that returns a WP_User instance that you can then use to extract the username.

<?php $user = get_user_by( $field, $value ); ?>

So you would call it like so

<?php $user = get_user_by( 'id', $user_ID ); ?>

If no user is found, get_user_by returns false.

You can also try the wp_get_current_user function that returns details about the currently logged in user, including the full name. It also sets the global variable $current_user. If no user is logged in, then 0 is returned and the global variable is set to 0.

<?php global $current_user;
      wp_get_current_user();

      echo 'Username: ' . $current_user->user_login . "\n";
      echo 'User email: ' . $current_user->user_email . "\n";
      echo 'User first name: ' . $current_user->user_firstname . "\n";
      echo 'User last name: ' . $current_user->user_lastname . "\n";
      echo 'User display name: ' . $current_user->display_name . "\n";
      echo 'User ID: ' . $current_user->ID . "\n";
?>

Upvotes: 15

Related Questions