5

Say for example my alias pattern for one node is set up as:

style-[node:field_style]/[node:title]

There may be a case that node:field_style is blank so I would like to use another field and a slightly different url alias pattern:

type-[node:field_type]/[node:title]

I am thinking about just using hook_pathauto_pattern_alter() but wondering if there is a better way?

1 Answer 1

7

I'd create a token for that specific data; I'm not sure it's necessarily better (or worse) than using the alter hook, but it has the advantage of being reusable elsewhere in the site.

A simple (untested) example:

function MYMODULE_token_info_alter(&$data) {
  $data['tokens']['node']['field_type_or_title'] = array(
    'name' => t('Field type or title'),
    'description' => t('Value from field_type if available, node title otherwise.'),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if (isset($tokens['field_type_or_title'])) {
      if ($items = field_get_items('node', $node, 'field_type')) {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($items[0]['value']) : $items[0]['value'];
      }
      else {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($node->title) : $node->title;
      }

    }
  } 
  return $replacements;
}
1
  • This answers this question and I'm sure other similar questions related to this topic. Amazing! Now, do you guys have an idea if we can return our token's value to be a combination of other previously defined tokens? This should make this answer even more useful. Thanks :-)
    – Mario Awad
    Oct 28, 2015 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.