Taxonomies

Taxonomies are the main way to categorize content in Drupal.

Taxonomies are used to group content in a specific category. For example, you can create a taxonomy term called "News" and then you can create a taxonomy term called "Sports" and then you can create a taxonomy term called "Politics". These are the main categories that you can use to group content. As opposed to nodes, taxonomy terms are not content, they are just categories.

Get Taxonomy Term Names

Method 1 - Using entityTypeManager

$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree(
  'grafica_ambito', // The taxonomy term vocabulary machine name.
  0,                 // The "tid" of parent using "0" to get all.
  1,                 // Get only 1st level.
  TRUE               // Get full load of taxonomy term entity.
);
$results = [];

foreach ($tree as $term) {
  $results[] = $term->getName();
}

Method 2 - Using EntityQuery

$results = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', "TAXONOMY_TERM")
    ->sort('FIELD')
    ->execute();

  $term_names_array = [];

  $term = \Drupal\taxonomy\Entity\Term::load($result);
  $term_names_array[] = $term->getName();

Method 3 - Same as method 2 but using entityTypeManager


$taxonomy_terms = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', "TAXONOMY_TERM")
    ->sort('FIELD');

$results = $taxonomy_terms->execute();

$term_names_array = [];

foreach ($results as $result) {
  $term = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->load($result);
  $term_names_array[] = $term->getName();
}

Last updated