Raw username token for Drupal 7

Oct 29, 2013 · by Tim Kamanin

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):

 * Provide information about our custom token.
function MODULE_NAME_token_info() {
  $info['tokens']['user']['name_raw'] = array(
'name' => t('Name: raw'),
'description' => t('Raw username taken straight from DB.'),
  return $info;

 * Provide replacement values for placeholder tokens.
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'user' && !empty($data['user'])) {
$user = $data['user'];
foreach ($tokens as $name => $original) {
  switch ($name) {
case 'name_raw':
  $replacements[$original] = $user->name;
return $replacements;

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.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials