Add CSS class to fields I have the following snippet.

function &lt;themename&gt;_preprocess_node(&amp;$vars) {
  if ($vars['teaser'] &amp;&amp; !$vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser';
  }
  elseif ($vars['teaser'] &amp;&amp; $vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser__front';
  }

  if (!$vars['teaser'] &amp;&amp; count($vars['field_related']) &gt; 2) {
    $vars['theme_hook_suggestions'][] = 'node__alt';
    foreach (element_children($vars['content']['field_related']) as $k) {
      $vars['content']['field_related'][$k]['#attributes']['class'][] = 'grid_1';
    }
  }
}


Basically, I have this field_related in my node that holds from 0 to 3 values. If it holds more than 2 values, I change the template suggestion (node__alt) and I'd like to attach a class (grid_1) to each of the values. I've spent the last 4 hours researching but nothing got me even near to where I want to go.

Do you have any idea?

EDIT In the template file I did like this:

&lt;aside id="related"&gt;
  &lt;?php foreach(element_children($content['field_related']) as $k) : ?&gt;
    &lt;div class="grid_1"&gt;
      &lt;?php echo render($content['field_related'][$k]) ?&gt;
    &lt;/div&gt;
  &lt;?php endforeach ?&gt;
&lt;/aside&gt;


It works, but it is far from being clean.
Make a copy of your_drupal_site/modules/field/theme/field.tpl.php in your theme directory and name it field--field_related.tpl.php  In this file  You can attach the class (grid_1) to each field as follows:

&lt;?php foreach ($items as $delta =&gt; $item) : ?&gt;        
&lt;div class="grid_1"&gt;&lt;?php print render($item); ?&gt;&lt;/div&gt;
 &lt;?php endforeach; ?&gt;


All the available variables are listed in the comments of this file so you will be able to customize as you like.

On any given node you can check how many fields have been created and theme according to that. You can change the above code to count how many fields are there on any node, the revised code is as follows:

&lt;?php foreach ($items as $delta =&gt; $item) : ?&gt; 
    &lt;?php
    if (count($items) &gt; 2) {
        print '&lt;div class="grid_1"&gt;' . render($item) . '&lt;/div&gt;';
    } else {
        print '&lt;div class="two_or_less"&gt;' . render($item) . '&lt;/div&gt;';
    }
    ?&gt;
&lt;?php endforeach; ?&gt;


This will add class "grid_1" to any node with 3 or more fields of field_related and add class "two_or_less" to the nodes with 1 and two fields.