Drupal 8: Limit an image field display in teaser mode to one image

Profile picture for user Phil Frilling
By Phil Frilling, 31 August, 2016

/**
 * Implements template_process_field().
 */
function THEME_preprocess_field(&$variables) {
  $element = $variables['element'];
  // Field type image
  if ($variables['field_name'] == 'FIELD_IMAGE' && $element['#view_mode'] == 'teaser') {
    // Reduce number of images in teaser view mode to single image
    $item = reset($variables['items']);
    $variables['items'] = array($item);
  }
}

Tags