how do I call my theme preprocess function for a specific field?

sibest picture sibest · Sep 28, 2011 · Viewed 23.1k times · Source

i'm on Drupal 7 and i have aspecific tpl.php file for a content field_image: "field--field_image.tpl.php". I need to create a preprocess function for this field and for my theme.

Supposing my theme name is "My Theme"

It should look like

function my_theme_preprocess_field(&$variables, $hook) {
  $variables['classes_array'][] = 'aClassName';
}

but it doesn't work. I am wrong. But where?

Thanks

Answer

Clive picture Clive · Sep 28, 2011

You can use template_preprocess_field() (like you do in your code above) but just test the particular field is the right one for you:

function my_theme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_image') {
      $variables['classes_array'][] = 'aClassName';
    }
  }
}

Once you've implemented the hook don't forget to clear your caches, hook implementations are cached in Drupal 7 so won't be picked up until the cache is cleared.