How to call the theme preprocess function for a specific field

drupaldrupal-7task-parallel-library

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

Best Answer

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.

Related Topic