Drupal 7 – Add Classes to fields in template preprocess field

This if a preprocess function that you will need to use again and again. So I thought it would make sense to have a template for it and save it as a code snippet on my blog. The template was inspired by many blogs and I added some of my own twist to it.

It starts with a few shortcuts to various variables that you will be able to modify based on the field machine name, bundle view mode etc. Mostly I used the function to add and manipulate classes on a field. Combining this function with a custom field tpl file makes it even more powerful.

Here is the snippet, enjoy.

// Template_preprocess_field
function YOURTHEME_clean_preprocess_field(&$vars){

  /* Set shortcuts to variables.*/
  if (!empty($vars['element'])) {

    $name = $vars['element']['#field_name'];
    $bundle = $vars['element']['#bundle'];
    $mode = $vars['element']['#view_mode'];

    // Shortcut to Classes
    $classes = &$vars['classes_array'];
    $title_classes = &$vars['title_attributes_array']['class'];
    $content_classes = &$vars['content_attributes_array']['class'];

    $item_classes = array();
    $item_class = "";

  }

  if($vars['element']['#field_name'] == 'YOUR_FIELD_MACHINE_NAME') {
    $classes[] = 'custom-class1';
  }

  if($vars['element']['#field_name'] == 'YOUR_FIELD_MACHINE_NAME_1') {
    $vars['label'] = t('Frequently Asked Questions');
  }

//   Do more stuff
//   $vars['item_class'] = $item_class;
//   // Apply odd or even classes along with our custom classes to each item */
//   foreach ($vars['items'] as $delta => $item) {
//     $vars['item_attributes_array'][$delta]['class'] = $item_classes;
//     $vars['item_attributes_array'][$delta]['class'][] = $delta % 2 ? 'even' : 'odd';
//   }

}