front and back-end web development, Leeds, UK

Richard's Blog - Design, coding and life in Japan


How to add your own Tokens from CCK fields in Druapl 7

If you want to add custom CCK field content such as taxonomy terms, categories and the like to other parts of your node automatically then you will need the help of Tokens. The standard install of Tokens in Drupal 7 will handle a few of the details like node titles and dates, but will not automatically provide you details of your CCK fields. So in order to do this you need to make your own custom tokens. This is especially useful when using the excellent Pathauto module or when trying to dynamically create meta keywords.

The Token API makes this very easy. In your own module you can start by listing the tokens you will be adding. In this case my node was based on a car entity for a car exporting website. The car has model which is a taxonomy term, a maker which is a parent of that term. It also has a year and a color which I am also wanting to add as token terms. These I will be adding to pathauto url alias' and meta tags for search engine optimization.

function mymodule_token_info($type = 'all') {
    $data['tokens']['node']['year'] = array(
      'name' => t('Year'),
      'description' => t('The cars\'s year.'),
    $data['tokens']['node']['maker'] = array(
      'name' => t('Maker'),
      'description' => t('The cars\'s maker.'),
    $data['tokens']['node']['model'] = array(
      'name' => t('Model'),
      'description' => t('The cars\'s model.'),
    $data['tokens']['node']['color'] = array(
      'name' => t('Color'),
      'description' => t('The cars\'s color.'),
    return $data;

I can now go and add the tokens and the replacements themselves using the hook_tokens method

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $model_taxonomy_term = taxonomy_term_load($node->field_model['en'][0]['tid']);
    $color_taxonomy_term = taxonomy_term_load($node->field_color['en'][0]['tid']);
    foreach (taxonomy_get_parents($node->field_model['en'][0]['tid']) as $maker_taxonomy) {}
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'year':
          $replacements[$original] = $node->field_year['en'][0]['value'];
        case 'maker':
          $replacements[$original] = $maker_taxonomy->name;
        case 'model':
          $replacements[$original] = $model_taxonomy_term->name;
        case 'color':
          $replacements[$original] = $color_taxonomy_term->name;
  return $replacements;

Here I have entered values of the node and its custom fields into the token. I can now add a url pattern using those patterns:



Recent Blog Posts