I have a view that outputs an image field. I would like to add a class to the .views-field div (for example, actually a views-row would also do the job) depending on whether the image is vertical (length > height) or horizontal (height > width).

I tried making a custom views-view-field-tpl.php for outputting the view's field, but I have no idea how to access the image or the image data.

EDIT: I've found that $field contains additional_fields, which in turns includes field_photo_width and field_photo_height. Those are arrays, though, and I have no idea how to get an actual value from them.

  • 1
    Arrays keys can be accessed with square brackets $array['value']. And object properties/methods can be accessed with an arrow $object->property. You can also have arrays inside objects: $node->field_body['value'].
    – Beebee
    Commented Jan 20, 2015 at 0:49
  • 1
    You might be better off using preprocessors in your theme's template.php file. This way you can do the calculation in a function, which is way neater.
    – Beebee
    Commented Jan 20, 2015 at 0:50
  • @Beebee : my problem is not about accessing arrays. Iexpected those to be simple numericals, representing the number of pixels, not an array
    – Dalmaz
    Commented Jan 26, 2015 at 14:45

1 Answer 1


The answer could be approached from various angles. Simpler perhaps would be to target the template_preprocess_image itself, and add a div wrapper around it with the class, or just add the class on the img tag. I chose to do it via template_preprocess_field.

function THEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_IMAGE_NAME') {
    foreach($vars['items'] as $key => $item){
      if (_add_image_proportions_class($item)) {
        if ($item['#item']['width'] > $item['#item']['height']) {
          $vars['classes_array'][] = 'landscape';
        else if ($item['#item']['width'] < $item['#item']['height']) {
          $vars['classes_array'][] = 'portrait';
        else {
          $vars['classes_array'][] = 'square';

function _add_image_proportions_class($item) {
  return $item['#image_style'] == 'medium';

_add_image_proportions_class() is just a function you implement to test whether you want to add the class or not. In my example, I targeted the image style that is applied to the image. You could for instance create a specific image style that is used only for that view, and target it specifically. Or you could test the path you are on, etc.

  • Could you tell me if it is possible to add those classes also to the wrapper?
    – Christoph
    Commented Feb 11, 2015 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.