Add Class to Image Field in Drupal 7

Matthew Dolman picture Matthew Dolman · Mar 11, 2011 · Viewed 12.1k times · Source

I have added an image field to content type "Basic Page" and using the "Manage Displays" option have it displayed at the top of the page. However there is no styling on the image and I can't for the life of me figure out how I add a class to the image so that I can add styles.

Answer

Matt F picture Matt F · Nov 8, 2011

The above answer helps if targeting CSS is your only need. But I needed to add a class to the IMG tag, period. Here's the way I solved the problem. This is probably not the best way, and certainly not the only, but it's a valid "Drupal way" and works. Open up the template.php file for your template.

Paste in the following function, which you will have to MODIFY and customize for your usage scenario. For example, you must replace <TEMPLATENAME> with your template name, and add or subtract classes as desired, and other things, as you'll see.

function <TEMPLATENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'Staff Photo' then assign additional classes to it:
    if ($variables['style_name'] == 'staff_photo') {
        $variables['attributes']['class'][] = 'lightbox';
        $variables['attributes']['class'][] = 'wideborder';
    }
}

I created an "if" statement to determine when the class should be added to the image, but you will have to customize that however you like--you might eliminate it entirely if you want a class on ALL image-field images, or you might say "if drupal_is_front_page()" if you only want it applied on the front page, etc.

In MY case, I created an image style (Configuration > Media > Image Styles) for Staff Photos and added the if clause to only apply my preferred classes to images of that specified Image Style. I think that's a great way to do it, but you can do what you like.

Now, whenever I am viewing a node which contains an image-field with image style of "Staff Photo," the classes magically appear in the IMG tag, which is just what I needed.