Tip #88: Creating Custom Tokens in Drupal
Tokens in Drupal are placeholders that get replaced with dynamic values. You’ve likely used tokens provided by core or contributed modules — like [node:title] or [user:name]. But what if you need a token that doesn’t exist? That’s where custom tokens come in!
✅ Why Create Custom Tokens?
Custom tokens allow you to:
🛠️ How to Create a Custom Token in Drupal
This defines your token group and the tokens it offers.
function mymodule_token_info() {
return [
'types' => [
'mymodule' => [
'name' => t('My Module'),
'description' => t('Custom tokens for my module.'),
],
],
'tokens' => [
'mymodule' => [
'current_time' => [
'name' => t('Current Time'),
'description' => t('The current server time.'),
],
],
],
];
}
This is where you define the actual value that should be returned.
function mymodule_tokens($type, $tokens, array $data = [], array $options = []) {
$replacements = [];
if ($type == 'mymodule') {
foreach ($tokens as $name => $original) {
switch ($name) {
case 'current_time':
$replacements[$original] = date('Y-m-d H:i:s');
break;
}
}
}
return $replacements;
}
Custom tokens won’t show up until you rebuild the cache. Run:
drush cr
📍 Where Can You Use These Tokens?
Custom tokens offer a lightweight, elegant way to plug your own logic into Drupal’s token system. They keep things reusable, dynamic, and integrated — the Drupal way. 🙌