drupal 7: how to create custom node token

Posted by admin on Sat, 11/11/2017 - 07:54

Here is the simple example how to create custom node token in Drupal 7.

Lets say you want to crete a custom node token that will return a first letter of the node title.

So at the first step you need to declare your node token using hook_token_info:

function MYMODULE_token_info() {
  $info['tokens']['node']['title_first_letter'] = array(
    'name' => t('Title first letter'),
    'description' => t('Generates first letter of node title')
  );
  return $info;
}

Then you need to create a processing of that token:

function slideaway_currency_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'title_first_letter':
          $replacements[$original] = substr($node->title, 0, 1); // get first letter of the title here 
          break;
      }
    }
  }
  return $replacements;
}

Don't forget to flush the cache to update token register.
That's it: go to the token list and it should be there!

Tags: 
×

Hey! Don't miss a new cool stuff!

Add new comment