1

I've created an image 'field_term_preview' field on the taxonomy vocabulary and trying to get this URL in my custom module:

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

foreach ($terms as $term) {
    if ($term->getName = 'Term with preview')
    {
        foreach ($term->getFields(true) as $field)
        {
            if ($field->getName() == 'field_term_preview')
            {
                var_dump($field->getValue());
            }
        }
    }
}

This code shows only target_id, alt, height, etc. enter image description here

How to get the URL to the preview image?

1

In Drupal images are File entities, the target_id is the File ID. So...

$fid = $field->getValue()[0]['target_id']; // File ID, 

// Note the [0] in the array. We assume there is always going to be 1 image here. 
// If your field allows more than 1 image, you will need to loop through each $field->getValue()

$file = \Drupal\file\Entity\File::load($fid); // load File entity object

$file_url = $file->url(); // get the URL.

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.