In this tuto, I'll show you how to load Taxonomy Terms by Level in drupal 8. using
loadTree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) function.
Parameters
string $vid: Vocabulary ID to retrieve terms for.
int $parent: The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.
int $max_depth: The number of levels of the tree to return. Leave NULL to return all levels.
bool $load_entities: If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.
Get only the 1st level
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('tags', 0, 1, TRUE);
$result = [];
foreach ($tree as $term) {
$result[] = $term->get('name')->value;
}
kint($result);
Get the 1st and 2nd levels
$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('tags', 0, 2, TRUE);
$result = [];
foreach ($tree as $term) {
$result[] = $term->get('name')->value;
}
kint($result);
Get only the 2nd level
$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, 2, TRUE);
$result = [];
foreach ($tree as $term) {
if (!empty($manager->loadParents($term->id()))) {
$result[] = $term->get('name')->value;
}
}
kint($result);
Get the 2nd and 3rd levels
$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, 3, TRUE);
$result = [];
foreach ($tree as $term) {
if (!empty($manager->loadParents($term->id()))) {
$result[] = $term->get('name')->value;
}
}
kint($result);
Get only the last level
$manager = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$tree = $manager->loadTree('tags', 0, NULL, TRUE);
$result = [];
foreach ($tree as $term) {
if (empty($manager->loadChildren($term->id()))) {
$result[] = $term->get('name')->value;
}
}
kint($result);