0

I've tried to change this code to show the term name instead of the term ID but now no term name or term id show at all

Orginal code for term ID

function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }   } } 

What I changed it too

function MYTHEME_preprocess_node(&$vars) {   if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $term_name = $info['term_name'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
        }
      }   } }

Many thanks for your help

1
3

To convert from $tid to term name, use taxonomy_term_load() to load the object, and then access $term->name:

$term = taxonomy_term_load($tid);
$term_name = $term->name;

Your function should look like:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
      foreach ($content['field_photo_topic']['#items'] as $index => $info) {
        $tid = $info['tid'];
        $term = taxonomy_term_load($tid);
        $term_name = $term->name;
        $content['field_photo_topic'][$index]['#href'] = 'photos/' . $term_name;
      }
    }
  }
}

Please note that this will only work the way you intend if you use PathAlias or similar to alias the path to be accessible by term name instead of numeric $tid.

1
  • Also, if your term names have capitals, spaces, or other characters that will make photos/foo bar baz "ugly", you may want to sanitize or otherwise clean it up. If this is the case, I like to just use pathauto_cleanstring() from the pathauto module to do it.
    – Jimajamma
    Apr 18 '14 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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