Tip #88: Creating Custom Tokens in Drupal

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:

  • Display dynamic data from your custom entities or fields.
  • Reuse logic across blocks, emails, paths, or metadata.
  • Maintain cleaner, more modular code.

🛠️ How to Create a Custom Token in Drupal

  • Implement hook_token_info()

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.'),
        ],
      ],
    ],
  ];
}        

  • Implement hook_tokens()

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;
}        

  • Clear the Cache

Custom tokens won’t show up until you rebuild the cache. Run:

drush cr        

📍 Where Can You Use These Tokens?

  • Token-based fields (e.g., Pathauto, Metatag)
  • Email templates
  • Custom blocks or rules
  • Programmatic token replacements

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. 🙌

To view or add a comment, sign in

Others also viewed

Explore topics