13

I want to load taxonomy terms by tid, but I didn't found how. Only how to load taxonomy by name, but now I have term id and I need to get value of fields.

I call this on public function build() for custom block.

My code:

$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('menu');
foreach ($terms as $term) {
    //var_dump($term->tid);
}
4
  • Check taxonomy_term_load_multiple
    – Jimmy Ko
    Commented Jul 3, 2016 at 22:12
  • Thx i use $entityManager->getStorage('taxonomy_term')->loadMultiple($terms);. But now all field (preperties) are private :'(
    – Kakoum
    Commented Jul 3, 2016 at 23:47
  • Yes, but you can get their values with the term methods, for example $name = $term->getName(); Look into the TermInterface to see which methods are available.
    – Maouna
    Commented Jul 4, 2016 at 15:19
  • The linked answer is very good - \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $parent, $max_depth, $load_entities); - the fourth function parameter allows to get back the actual term objects, not just the tids.
    – Andreas
    Commented Jan 11, 2023 at 11:57

2 Answers 2

20

in Single Manner

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(TID);
    $value = $term->FIELD_MACHINENAME->value;

Example : load title and language of term id =2

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2);
    $title = $term->name->value;
    langcode = $term->langcode->value;

And for load Multiple as you wanted

  $terms = $entityManager->getStorage('taxonomy_term')->loadMultiple($t‌​erms);
  foreach ($terms as $term) {
      var_dump($term->tid->value); //return tid of term
   var_dump($term->name->value); //return title of term
  }
2
  • loadMultiple($t‌​erms)... what is $terms
    – AlxVallejo
    Commented Jan 24, 2018 at 19:17
  • @AlxVallejo An array of taxonomy term IDs.
    – mbomb007
    Commented Oct 5, 2022 at 14:28
9

You can also do like this:

$tids = [1,2,3];
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);

Example from : http://www.drupal8.ovh/en/tutoriels/17/get-taxonomy-terms-of-a-vocabulary-drupal-8

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