Drupal 7 modifying field output before rendering

Snippet

Or, how to add a # to a tag vocabulary field, making it a #hashtag

#hashtag!

Okay, there are times when you want to modify the text or value of a field before dumping it on the page. Sometimes, for whatever reason, you can't do it in a place other than just before rendering. Take, for example, the case of tags. Maybe you want to add a # in front of the tag text so that it looks like a #hashtag.

In this case, you want to use the template_preprocess_field function.

To use, add the following HTML to your theme's template.php file, changing THEME to your theme's name, FIELDNAME to the name of the field you want to modify, and the modification you want to do.

/**
 * template_preprocess_field()
 * https://api.drupal.org/api/drupal/modules%21field%21field.module/function/template_preprocess_field/7
 *
 * @param array $vars
 * @param string #hook
 */
function THEME_preprocess_field(&$vars, $hook) {
  $element = $vars['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_FIELDNAME') {
      foreach ($vars['element']['#items'] as $i => $e) {
        // this is where the manipulation actually happens.
        $vars['items'][$i]['#title'] = '#' . $vars['items'][$i]['#title'];
      }
    }
  }
}