[Drupal] How to create custom Tokens in Drupal 6?

| | 2 min read

There may be many situations while working on a Drupal site where you need to create custom tokens for a variety of applications within Drupal. If you are faced with the same scenario in your Drupal site and want to know how to create custom tokens in a Drupal 6 website then read on to know more.

Drupal Tokens

Tokens are basically pieces of text which are provided by the Drupal Token module. Tokens can be used in the form of placeholders in our Drupal sites url aliases and documents. In Drupal there are many built-in tokens.

Some of the tokens and their placeholders are:

Tokens      Placeholders
[nid]       %nid
[user]      %user

The above tokens are provided by default by the Drupal core.

Creating Custom tokens for your Drupal website

If you want to create your custom tokens, that is possible too. Check out the steps below to do that.

  1. Implement hook_token_list. Suppose you want to create a token named 'listingid'. Then you may declare it inside hook_token_list() as a global token variable so that it will be available anywhere.
  2. /**
    * Implementation of hook_token_list() .
    */
    function hook_token_list($type = 'all') {
      $tokens['global']['listingid'] = t('The current listing id');
      return $tokens;
    }
  3. Define the value of the token(Placeholder to be used). To define the value, you have to implement hook_token_values().
  4. /**
    * Implementation of hook_token_values() .
    */
    
    function hook_token_values($type, $object = NULL, $options = array()) {
      $values = array();
      switch ($type) {
      case 'global':
      $values['listingid'] = $_SESSION['agent_listing_id']; // Creating a session
      // variable and assigning it to our token.
      }
      return $values;
    }

    Now you have created your custom token. You can use %agent_listing_id as place holder for the token 'listingid'. Hope that helps. If you have any feedback regarding the article use the comment form below.