I need the $user object within a module am creating. But am not able to get it. I have created a module that extends user object hold more data. Its working fine. I am also able to use this values in theme files. But am not able to get it in any function within a module.

The standard value $user->name; or my custom value $user->data['privacy']; nothing is available in module.

I tried using this

global $user;
$user = $user->name;

What is the mistake here? Is it that global is not the right way to get the user object?


You're currently referencing the global $user object, then in the very next line you're overwriting it with a string (the username). So your global $user object is destroyed, and you will probably be logged out of the site (as well as the code not working as expected).

You're referencing the global user object in the correct way, but by default it isn't fully loaded (i.e. with fields attached, etc). To get the extra data you should use the user_load() function like so:

global $user;

// Get the fully loaded user object
$account = user_load($user->uid);

// Get the username. Make sure you don't override the global $user object here!
$username = $account->user.

// Get a field value.
$field_items = field_get_items('user', $account, 'field_foo');
  • We used global because we were not able to get $user in module. How am i suppose to get user_id now? I am able to get all these in templates.
    – esafwan
    Jun 16 '12 at 8:20
  • I'm really not sure what you mean, the global $user object is available everywhere...it's a global. From anywhere in your code use: global $user; $uid = $user->uid;
    – Clive
    Jun 16 '12 at 10:17

I had the same problem, and I fixed it with the following code.

 module_load_include('pages.inc', 'user', 'user');
 global $user;
  • 1
    The $user global isn't declared in user.pages.inc, loading that file won't make any difference
    – Clive
    Jun 15 '12 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.