Last active
February 21, 2017 15:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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