Programmatically display user names according to the user profile type This is a Drupal 7 site. I have a profile2 module installed with several profile types for different users. The user name should be displayed according to the profile type:


For personal users - the user name should be build from the first and last name fields.
For business users, the user name should be taken from the business name field.


How do I display user names programmatically?
I've put the following code on a module: 

&lt;?
// Find the type of the current user
function mymodule_get_usertype(&amp;$user) {
  $usertype = 'other';
  if (is_array($user-&gt;roles) &amp;&amp; 
      in_array('authenticated user', array_values($user-&gt;roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user-&gt;roles) &amp;&amp; 
          in_array('non authenticated user', array_values($user-&gt;roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user-&gt;roles) &amp;&amp; 
          in_array('business', array_values($user-&gt;roles))) {
    $usertype = 'business';
  }
  return $usertype;
}

// Implements hook_username_alter,
// to display the user name according to the profile type
function mymodule_username_alter(&amp;$name, $account) {

  $profile_type = mymodule_get_usertype($account);
  if (!empty($profile_type)) :
    $profiledata = profile2_by_uid_load($account-&gt;uid, $profile_type);
  endif;

  if ($profiledata) :

    switch ($profile_type) {
      case 'individual':
        $firstname = field_get_items('profile2', $profiledata, 'field_first_name');
        $firstname = $firstname[0]['safe_value'];
        $lastname = field_get_items('profile2', $profiledata, 'field_last_name');
        $lastname = $lastname[0]['safe_value'];
        $name = "$firstname $lastname" ;
        break;

      case 'business':
        $bizname = field_get_items('profile2', $profiledata, 'field_biz_name');
        $bizname = $bizname[0]['safe_value'];
        $name = $bizname;
        break;

      default:
        // For admin users, no change
    }
  endif;
}
?&gt;


The result is that the new name is displayed whenever a user name is displayed (e.g. on the menus, on the user page, or on the user listing pages)