Custom user name from profile

Current project I am working on has user profiles using profile2 module. So it is pretty common task to replace all links/references on the site with user's proper name from Profile instead of his drupal username.

This is really easy to achieve using hook_username_alter()

 * Implements hook_username_alter().
function mymodule_username_alter(&$name, $account) {
  $contact_profile = profile2_load_by_user($account, MYMODULE_PROFILE_CONTACT_TYPE);
  if (isset($contact_profile->field_name[LANGUAGE_NONE][0]['value'])) {
    $name = $contact_profile->field_name[LANGUAGE_NONE][0]['value'];

And if you will want somewhere in the code display user's name do this using function format_username().


A code-less alternative would be to use the RealName module that allows to use tokens to form the display name.

Post this to too, so the snippets can be centralized.

If you don't want to code your own, check out the