Search code examples
phpdrupaldrupal-7drupal-theming

Drupal 7 - add the same class to all <img> tags in the content area


I have an online Portfolio site that I transferred from a static HTML into Drupal 7 - trying to learn Drupal. I have 3 separate pages that have image galleries. I have a javascript (.js) file that adds reflections onto any image that carries a class="reflect". In HTML, this is easy to do, obviously, and it was working just fine in my static site. I would like to continue using it, but I cannot for the life of me figure out how to add the required class to my images.

Desired Result:

<img src="image.jpg" class="reflect" />
<img src="image2.jpg" class="reflect" />
<img src="image3.jpg" class="reflect" />

and so on...

Addressing other found suggestions: All of my images currently do not carry a class at all. I did find a couple of proposed work-around's but they didn't quite suit my needs as I need to add the same class to all of the tags present, while ignoring any elsewhere, such as the header and footer. Plus, while I know a little PHP, I'm not great at it. Drupal is supposed to be completely dynamic so I'm sure there's a way to do this, but I'm at a loss.


Solution

  • You can implement theme_image() to do that, in your template.php file just type the following:

    function [YOUR_THEME]_image($variables)
    {
        $attributes = $variables['attributes'];
        $attributes['src'] = file_create_url($variables['path']);
    
        $attributes['class'][] = 'reflect'; // add the class name here
    
        foreach (array('width', 'height', 'alt', 'title') as $key) {
    
            if (isset($variables[$key])) {
                $attributes[$key] = $variables[$key];
            }
        }
    
        return '<img' . drupal_attributes($attributes) . ' />';
    }
    

    Kindly note that this class will be added to all the images across the site.

    Hope this helps... Muhammad.