I have a node and want to get all the taxonomy terms assigned to the node.

In drupal 6 I could use $node->taxonomy and the taxonomy_* functions but these don't exist in drupal 7.

Comments

Anonymous’s picture

Something like this should do it:

$node = node_load($nid);
$tids = array();
foreach ($node->field_term_reference['und'] as $item) {
  $tids[] = $item['tid']
}
$terms = taxonomy_term_load_multiple($tids);

Just replace 'field_term_reference' with the name of your term reference field, and replace 'und' with the page's current language code if you have multiple languages.

There's probably a shorter way but I haven't come across it yet.

WorldFallz’s picture

yowza-- i wonder how this is an improvement from $terms = taxonomy_node_get_terms($nid);, lol.

Anonymous’s picture

Couldn't agree more! It kind of makes sense I guess as terms references are now fieldable so to keep a good degree of separation node specific functions shouldn't really be in the taxonomy module.

Having said that though, taxonomy keeps its own node index and provides some node functions so go figure! This should serve as a decent enough replacement for anyone who misses the old function:

function taxonomy_node_get_terms($node, $key = 'tid') {
  $terms = &drupal_static(__FUNCTION__, array());
  
  if (!isset($terms[$node->nid][$key])) {
    $query = db_select('taxonomy_index', 'i')
      ->fields('i', array('tid'))
      ->condition('i.nid', $nid)
      ->orderBy('v.weight')
      ->orderBy('t.weight')
      ->orderBy('t.name');

    $query->join('taxonomy_term_data', 't', 't.tid = i.tid');
    $query->join('taxonomy_vocabulary', 'v', 'v.vid = t.vid');
    
    $terms = taxonomy_term_load_multiple($query->execute()->fetchCol());
    $terms[$node->nid][$key] = array();
    foreach ($terms as $term) {
      $terms[$node->nid][$key][$term->$key] = $term;
    }
  }
  
  return $terms[$node->nid][$key];
}

--EDIT--
Updated to better reflect the original function. Beware though, this isn't safe to use with node revisions; to do that would involve more complex db calls. There is a module that might be able to help with this though: http://drupal.org/project/taxonomy_entity_index