I used this code to get the parent ids , but the result is a huge object . how do I get the parent id's and term names from the resulting object ?

 $ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);

1 Answer 1


In $ancestors you'll find an array of the parent terms starting with the term $tid itself:

$ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);
$list = [];
foreach ($ancestors as $term) {
  $list[$term->id()] = $term->label();
  • 1
    Does the field_fieldname go where it says $tid? example = loadAllParents($field_myvocab); Do I need to create a variable? Commented May 2, 2018 at 16:07
  • 3
    If you start with a node: $field_myvocab = $node->field_myvocab; $tid = $field_myvocab->target_id. If you have multiple terms stored in the field you can use the field variable as an array and loop over it.
    – 4uk4
    Commented May 2, 2018 at 19:31
  • 2
    what happens for the first level of taxonomy terms (the ones which does not have parent)?
    – shekoufeh
    Commented May 29, 2019 at 13:44

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