custom tokens in drupal 7
Blog

How to create custom tokens in Drupal 7

One of the great feature in drupal is tokens system. Tokens are reusable text that can be placed into documents via simple placeholders, like %site-name or [user]. In Drupal there are many default tokens are made available thru’ token module e.g. nodes, users, taxonomy as well as other site related tokens. For example to display site name we have [site:name] token, to display node author we have [node:author]. All these tokens are properties of entities. And if we add new field in node then these field will be available as token. For example [node:body] is the token where it will display body field.

But quite a few times we come across situation when default tokens available in Drupal is not enough for project. Today we are going to discuss about how to create custom tokens using our custom module. In our example we will create a token Trimmed body field. This will display 20 characters of body field in a node wherever we will use this token.

To achieve these we will be using hook_token_info() and hook_tokens() hooks Create a new module MY_MODULE and implement these two hooks. But before start implementing this let’s discuss about hook_token_info() and hook_tokens() hooks.

hook_token_info()

These hook provides information about available placeholder tokens and token types. Tokens are placeholders that can be put into text by using the syntax [type:token], where type is the machine-readable name of a token type, and token is the machine-readable name of a token within this group.

Return value properties:

These function will return associative array of available tokens and token types.

types

  • name: Name of the token type.
  • description: Description of the token type.
  • needs-data: The type of data that must be provided to token_replace() in the $data argument (i.e., the key name in $data) in order for tokens of this type to be used in the $text being processed.

tokens

  • name: Name of the token.
  • description: Description of the token.
  • type (optional): A 'needs-data' data type supplied by this token, which should match a 'needs-data' value from another token type. For example, the node author token provides a user object, which can then be used for token replacement data in token_replace() without having to supply a separate user object.

hook_tokens()

These hook provides replacement values for placeholder tokens. This hook is invoked when someone calls token_replace(). That function first scans the text for [type:token] patterns, and splits the needed tokens into groups by type.

Return value properties :

$type: The machine-readable name of the type (group) of token being replaced, such as 'node', 'user', or another type defined by a hook_token_info() implementation.

$tokens: An array of tokens to be replaced. The keys are the machine-readable token names, and the values are the raw [type:token] strings that appeared in the original text.

$data: (optional) An associative array of data objects to be used when generating replacement values, as supplied in the $data parameter to token_replace().

$options: (optional) An associative array of options for token replacement; see token_replace() for possible values.

Create MY_MODULE module & create file MY_MODULE.tokens.inc and implement following code.

/**
 * Implements hook_token_info().
 */
  function custom_title_token_info() {

    // Define token value, body_trim is the token will be used as [node:body_trim]
    $node_trim['body_trim'] =  array(
      'name' => t("Trimmed body field"),
      'description' => t("Trim body field to 20 characters "),
    );

    // Return associative array of tokens & token types
    return array(
      'tokens' => array(
        'node' => $node_trim,
      ),
    );
}

/**
 * Implements hook_tokens().
 */
function custom_title_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  // Check if token type is node
  if($type == 'node'){
    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Check token is body_trim
        case 'body_trim':
          $body = $data['node']->body[LANGUAGE_NONE][0]['value'];
          // Trim 20 characters and return
          $replacements[$original] = substr($body,0,20) . ' ...';
          break;
      }
    }
  }
  return $replacements;
}

Note : We have not defined any custom token type as we needed node related token.

Reference:
function hook_token_info
function hook_tokens