2

I have some taxonomy terms that have an image field in them. I am trying to get the value of the image field in my templates. How can I do this? The field's name is field_header_image.

I have this so far but it does not work..

$headerimg = field_view_field('taxonomy_term', $term, 'field_header_image'); 
print render($headerimg);

I'm guessing I need something else for taxonomy_term but I'm not sure what that should be.

9

You can get it like this :

$term = taxonomy_term_load($tid);
$field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
if ($field_header_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
}
print render($headerimg);

If you want to use an image_style :

$headerimg = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'my_image_style', //place your image style here
  ),
));

Here is a contextual answer if you are on your taxonomy term page.

In your file template.php use the theme_preprocess_page function like this :

function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

Then in you page.tpl.php you can print render($headerimg);

  • field_get_items('taxonomy_term', $term, 'field_header_image') does not return anything for me. It just generates an error that says "Error. The website encountered an unexpected error. Please try again later." – Dustin Jul 7 '14 at 15:17
  • how do you get your $term object ? You need to have taxonomy_term_load or something before. Can you check the Drupal logs ? – pbonnefoi Jul 7 '14 at 15:23
  • I don't know. I'm just using some example code that I found. I've never done this before. – Dustin Jul 7 '14 at 16:57
  • I edited my answer, all you need to have is the tid. PLMK if you have some errors (Drupal Logs would help) – pbonnefoi Jul 7 '14 at 17:39
  • Ok here are the errors in the log... EntityMalformedException: Missing bundle property on entity of type taxonomy_term. Notice: Undefined variable: tid in include() – Dustin Jul 7 '14 at 17:48

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.