How to get custom fields assigned to taxonomy in Drupal 8. What I have done so far is:

$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');

$contact_countries now holds taxonomies, I can get name of taxonomy and ID, but I also created custom field in taxonomy, how can I get it?

With this code

foreach($contact_countries as $contact_countrie) {
        $terms[] = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid);
        $variables['contact_countries'] = $terms;

I'm getting object(Drupal\taxonomy\Entity\Term) with protected values. I can see my custom fields values there but can't access it.

  • What do you mean by 'created a custom field in taxonomy'? can you explain further? – Matt Mar 23 '17 at 20:49

You can access fields using getFields() on the term object: https://api.drupal.org/api/drupal/core!modules!taxonomy!src!Entity!Term.php/class/Term/8.2.x

Or you can use get(): https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21ContentEntityBase.php/function/ContentEntityBase%3A%3Aget/8.2.x


I done it like this:

$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');

$terms = array();

foreach($contact_countries as $contact_countrie) {
    $terms[] = array(
        'contact_country' => $contact_countrie->name,
        'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
        'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,

Here I have fields field_phone (text field) and field_category_flag (file field).


I did it this way.

$countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('countries',0,NULL,TRUE);

/* Using First Country : $countries[0] */
$region = $countries[0]->get('field_region')->target_id;
$description = $countries[0]->get('field_description')->value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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