Drupal - Get custom fields assigned to taxonomy

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).


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 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;