Skip to content Skip to navigation

Showing Only the First Image in the Teaser for a Drupal 7 Image Field

« previous next »

By default, a Drupal 7 image field that is set to contain multiple images, will display all of the images in both the teaser and full node view. While desirable, there is no option when creating a view to only show the first image in the teaser. This can be accomplished, however, with the new Drupal 7 field-level template-hint.

In order do this globally for a field named "field image" the following code in a template file named "field--field_image.tpl.php"

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
 <?php if (!$label_hidden) : ?>
   <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
 <?php endif; ?>
 <div class="field-items"<?php print $content_attributes; ?>>
 <?php if ($element['#view_mode']=="teaser") { ?>
     <div class="field-item even"<?php print $item_attributes[0]; ?>><?php print render($items[0]); ?></div>
 <?php } else { ?>
   <?php foreach ($items as $delta => $item) : ?>
     <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
   <?php endforeach; ?>
  <?php } ?>

UPDATE: Note that the views module now includes an option for which values to display out of multi-value fields that takes precedence over the field-level template hint.

Facebook Comments