Drupal 7: Get Taxonomy Name by Id

While working on Drupal, we may need to get taxonomy term name from its id. In Drupal 7, the easiest way would be to call taxonomy_term_load().

taxonomy_term_load() will return taxonomy term object containing all term properties.

Sometimes, we may need more efficient method of getting term name without the heaviness of other properties of that term. And there is no such function in Drupal 7.

Here is a function that help you to get just taxonomy term name by its id.

function taxonomy_get_term_name_by_id($tid) {
  return db_query('SELECT name FROM {taxonomy_term_data} WHERE tid = :tid', array(':tid' => $tid))->fetchField();
}

It will return term name if that term exists or FALSE will be returned.

For better performance, adding static cache would be good. So calling the function more that once for same term will hit the database only once.

function taxonomy_get_term_name_by_id($tid) {
  $term_names = &drupal_static(__FUNCTION__);
  if (!$term_names) {
    $term_names = array();
  }
  elseif (isset($term_names[$tid])) {
    return $term_names[$tid];
  }
  $term_name = db_query('SELECT name FROM {taxonomy_term_data} WHERE tid = :tid', array(':tid' => $tid))
    ->fetchField();
  if ($term_name) {
    $term_names[$tid] = $term_name;
  }
  return $term_name;
}