Is it possible to render a user's username differently to different users?

Here's the use case: I have a username with a user's First + Last name (created using the Realname module). In the user's profile, I have a setting for 'name privacy' - if the user wants to keep his last name private, the name should show as just 'First' instead of 'First + Last' to anyone who is not a site admin.

Would hook_username_alter() work for this purpose? It seems that is not dynamically loaded, but rather is cached when the user object is cached... so it couldn't simultaneously display 'First' to one user and 'First Last' to another user.

1 Answer 1


Reference: http://drupal.org/node/1194546

Basically, the easiest way to do this involves a couple steps:

First, implement hook_username_alter() in your custom module to change the username dynamically, depending on the context of the username's display (you can, for example, load the global $user object and display one form of the account in question's name to $user's with the role 'teacher', and another form to $user's with the role 'authenticated'...

Second, you will only be able to dynamically control the username as returned by $user->name or by theme('username', account) using hook_username_alter(). You can't change a username dynamically via realname, because that module stores the name in the database and caches it for performance reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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