How do I get the parent tid of a taxonomy term in Drupal 8
You can pull the tree for the vocabulary and sift through that.
// assuming $termId is the child tid..
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('VOCABULARY_NAME', 0);
for ($tree as $term) {
if (in_array($termId, $term->parents)) {
$parent_term = $term;
break;
}
}
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term_id);
$parent_term_id = $term->parent->target_id;
It will provide the parent id of the term if exist.
Now that you have the term parent with the code:
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($termId);
$parent = reset($parent);
You can simply use the $parent->id()
method to get your parent tid.
$parent_tid = $parent->id()