Skip to content

Instantly share code, notes, and snippets.

@vensires
Last active February 21, 2017 15:04
Show Gist options
  • Save vensires/6db126f073be0e05c68e600500ebb151 to your computer and use it in GitHub Desktop.
Save vensires/6db126f073be0e05c68e600500ebb151 to your computer and use it in GitHub Desktop.
When an image field displays an image with empty *alt* or *title* attributes, these get filled with the label of the corresponding entity. Using hook_preprocess_field() we target view mode displays but not Views using fields. hook_field_attach_view_alter() though targets everything. This code may play well in both a module and a theme.
<?php
/**
* Implements hook_field_attach_view_alter().
*
* It fills the empty "alt" and "title" attributes of images with the label of
* the corresponding entity.
*/
function mymodule_field_attach_view_alter(&$result, $context) {
if (!empty($context['entity_type']) && !empty($context['entity'])) {
$label = entity_label($context['entity_type'], $context['entity']);
$fields = element_children($result);
foreach ($fields as $field) {
if ($result[$field]['#field_type'] == 'image') {
$items = element_children($result[$field]);
foreach ($items as $item) {
if (isset($result[$field][$item]['#item'])) {
if (empty($result[$field][$item]['#item']['alt'])) {
$result[$field][$item]['#item']['alt'] = $label;
}
if (empty($result[$field][$item]['#item']['title'])) {
$result[$field][$item]['#item']['title'] = $label;
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment