taxonomy_node_get_terms_by_vocabulary replacement for drupal 7


taxonomy_node_get_terms_by_vocabulary() is not available in Drupal 7. I discovered this when I tried to install the Tweet Module whose D7 branch still relies on it. I re-wrote the D6 version of the function for D7 which returns the same array of term objects. This should help module maintainers port their D6 modules to D7. If there is a better D7 way to do this please let me know in the comments. UPDATE: There is now a patch based on this code for the tweet module as well.  

Drupal 7 Version you can include in your module
<?php
function _taxonomy_node_get_terms_by_vocabulary($node$vid$key 'tid') {
  
$result db_query('SELECT t.tid, t.* FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight', array(':vid' => $vid':node_nid' => $node->nid));
  return 
$result->fetchAll();
}
?>
Drupal 6 version included in Core
<?php
function taxonomy_node_get_terms_by_vocabulary($node$vid$key 'tid') {
  
$result db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight''t''tid'), $vid$node->vid);
  
$terms = array();
  while (
$term db_fetch_object($result)) {
    
$terms[$term->$key] = $term;
  }
  return 
$terms;
}
?>
© 2011 Adam Gerson.