4.6.x taxonomy.module taxonomy_get_parents($tid, $key = 'tid')
4.7.x taxonomy.module taxonomy_get_parents($tid, $key = 'tid')
5.x taxonomy.module taxonomy_get_parents($tid, $key = 'tid')
6.x taxonomy.module taxonomy_get_parents($tid, $key = 'tid')
7.x taxonomy.module taxonomy_get_parents($tid)

Finds all parents of a given term ID.

Parameters

$tid: A taxonomy term ID.

Return value

An array of term objects which are the parents of the term $tid, or an empty array if parents are not found.

6 calls to taxonomy_get_parents()
TaxonomyQueryAlterTestCase::testTaxonomyQueryAlter in modules/taxonomy/taxonomy.test
Tests that appropriate tags are added when querying the database.
TaxonomyTermTestCase::testTaxonomyTermHierarchy in modules/taxonomy/taxonomy.test
Test terms in a single and multiple hierarchy.
TaxonomyTermTestCase::testTermMultipleParentsInterface in modules/taxonomy/taxonomy.test
Test saving a term with multiple parents through the UI.
taxonomy_form_term in modules/taxonomy/taxonomy.admin.inc
Form function for the term edit form.
taxonomy_term_delete in modules/taxonomy/taxonomy.module
Delete a term.

... See full list

1 string reference to 'taxonomy_get_parents'
taxonomy_terms_static_reset in modules/taxonomy/taxonomy.module
Clear all static cache variables for terms.

File

modules/taxonomy/taxonomy.module, line 1020
Enables the organization of content into categories.

Code

function taxonomy_get_parents($tid) {
  $parents =& drupal_static(__FUNCTION__, array());
  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query
      ->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query
      ->addField('t', 'tid');
    $query
      ->condition('h.tid', $tid);
    $query
      ->addTag('taxonomy_term_access');
    $query
      ->orderBy('t.weight');
    $query
      ->orderBy('t.name');
    $tids = $query
      ->execute()
      ->fetchCol();
    $parents[$tid] = taxonomy_term_load_multiple($tids);
  }
  return isset($parents[$tid]) ? $parents[$tid] : array();
}

Comments

bucefal91’s picture

I guess it's worth to mention that this function returns array keyed by parents' tid, because it makes a call to taxonomy_term_load_multiple()

codesidekick’s picture

This script will only load the immediate parent of the term and not the parents parent etc. For that you need taxonomy_get_parents_all

graceman9’s picture

emarchak’s picture

To do this in drupal 8 you need TermStorage::loadParents()

$storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
$parents = $storage ->loadParents($term->id());