Search code examples
arraysdrupal-8drupal-taxonomy

Drupal - Get custom taxonomy fields


I am trying to get a custom field assigned to taxonomy. I have tried this:

$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);

$terms is now storing all the terms from the vocabulary called 'zeme'. The problem is when I print this variable, it doesnt show the custom field that I need to get. Any idea how can I get this custom field? My code looks like this:

 $vid = 'zeme';
  $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid); 
  foreach ($terms as $term) {
    $term_data[] = array(
      'id' => $term->tid,
      'name' => $term->name
    );
  }

Solution

  • Here is the loadTree function official documentation : TermStorage::loadTree

    When you use the loadTree function, it will only get you the minimal datas to save execution time. You can see there is a $load_entities parameter set to false by default.

    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.

    So if you want to get all the datas of each of your taxonomy terms, you have to set $load_entities to true.

    $vid = 'zeme';
    $terms =\Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadTree($vid, 0, null, true);