[Drupal] How to create a custom token in a Drupal 7 site and set a custom value for it?

| | 1 min read

If you are a Drupal developer you must have noticed that there is very little information on the web regarding how to create a custom token in a Drupal site. We needed to create a custom token for one of our Drupal clients. If you are facing a similar situation in your Drupal site and would like to know how to create a custom token in your Drupal 7 site and set a custom value for it then read on to know the complete solution

To create new custom tokens we have to use the 'hook_token_info()' hook. Have a look at the example of the hook shown below.

function MY_MODULE_token_info() {
  $info['tokens']['node']['time-to-expire'] = array(
    'name' => t('Expiry Time'),
    'description' => t('Expiry time'),
  );
  return $info;
}

This will create a custom token [node:time-to-expire]. Next we can set any custom value for this token using the hook function 'hook_tokens_alter()'.

function MY_MODULE_tokens_alter($replacements, $context) {
  $replacements['[node:time-to-expire]'] = '2012-12-28'; 
}

Now wherever this token [node:time-to-expire] is used, it will get replaced by the date '2012-12-28'. This is just an example to show how we can create a new token and set a custom value for it. Hope this is helpful for someone. Please send in your feedback as comments.