How to get taxonomy term field values I have created vocabulary "Hospital" and created text and image fields like:


Hospital Image: (machine name: field_hospital_image) // image field
Hospital Contact: (machine name: field_hospital_contact_no_) // text field


My code is:

$vid = 'hospitals';
$terms = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid);
foreach ($terms as $term) {
  $term_data[] = [
    'tid' =&gt; $term-&gt;tid,
    'tname' =&gt; $term-&gt;name,
    'image' =&gt; ...???..,    // image field
    'contact' =&gt; ...???..,  // text field
  ];
}


Please suggest namespace also.

I alsready tried :

'contact' =&gt; $term-&gt;get('field_hospital_contact_no_')-&gt;getValue(),


and

'contact' =&gt; $term-&gt;get('field_hospital_contact_no_')-&gt;value,


Errors:


  Error: Call to undefined method stdClass::get()
Term object is not loaded with loadTree by default a basic php object is loaded instead.

You have to load the term object for each term using $term_obj = Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load($term-&gt;tid);

Your code should look like this

$vid = 'hospital';
$terms = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid);
foreach ($terms as $term) {
  $term_obj = Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load($term-&gt;tid);
  $url = "";
  if(isset($term_obj-&gt;get('field_hospital_image')-&gt;entity)){
    $url = file_create_url($term_obj-&gt;get('field_hospital_image')-&gt;entity-&gt;getFileUri());
  }

  $term_data[] = [
    'tid' =&gt; $term-&gt;tid,
    'tname' =&gt; $term-&gt;name,
    'contact' =&gt; $term_obj-&gt;get('field_hospital_contact_no_')-&gt;value,
    'image_url' =&gt; $url,
  ];
} 


NOTE: Alternatively you can also use loadTree($vid, 0, NULL, TRUE) to load the entities directly on the $terms array but perhaps it should be avoided on very large vocabularies.  More info on the loadTree method