🇬🇧
Drupal Documentation and Guides
Guides
English
English
  • Getting Started with Drupal
  • Installing Drupal
  • Drush
  • Theme & Module Development Concepts
  • Modules
  • Themes
  • FrontEnd
    • Javascript
  • Backend
    • Helpful Drupal Classes and Methods
    • Entities
    • Nodes
    • Taxonomies
    • Hooks
    • Twig
    • Libraries
    • Queries
    • Forms
    • Files & Images
    • Helpful functions and solutions
  • Guides
    • Custom Fields
      • Entity Reference and integer
      • Two Text Fields
      • Textfields, formatted text and numbers
      • Links and media elements
Powered by GitBook
On this page
  • Get Taxonomy Term Names
  • Method 1 - Using entityTypeManager
  • Method 2 - Using EntityQuery
  • Method 3 - Same as method 2 but using entityTypeManager
  1. Backend

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();
}

PreviousNodesNextHooks

Last updated 2 years ago