Raw username token for Drupal 7

There are situations, when you or other modules alter username via hook_username_alter() and this can change username dramatically: for example, you can alter username into a combination of First and Last Name, etc. Looks nice, but there's a problem, it will alter username into First and Last Name everywhere, even in admin emails being sent out to users upon registration and instead of real username your users will get an altered username in their mail which is sometimes not good.

So what can be done? Hassling with hook_username_alter() and trying to catch cases when you can alter or not username isn't pleasant and here when tokens come to rescue. You can create a custom raw username token which holds unaltered username taken directly from database. Then you can put this token everywhere you need an unaltered username including admin emails.

Let's prepare our custom token, this is simple, put the code below into your custom module (don't forget to replace MODULE_NAME with your module name):

  1. /**
  2. * Provide information about our custom token.
  3. */
  4. function MODULE_NAME_token_info() {
  5. $info['tokens']['user']['name_raw'] = array(
  6. 'name' => t('Name: raw'),
  7. 'description' => t('Raw username taken straight from DB.'),
  8. );
  9. return $info;
  10. }
  11. /**
  12. * Provide replacement values for placeholder tokens.
  13. */
  14. function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  15. $replacements = array();
  16. if ($type == 'user' && !empty($data['user'])) {
  17. $user = $data['user'];
  18. foreach ($tokens as $name => $original) {
  19. switch ($name) {
  20. case 'name_raw':
  21. $replacements[$original] = $user->name;
  22. break;
  23. }
  24. }
  25. return $replacements;
  26. }
  27. }

And clear the cache. You should now have a User: Name Raw token available in the token list. Put it anywhere you need an unaltered username to be shown and profit! You can find and clone this snippet here: http://dropbucket.org/node/905.