How to add classes to images based on their categories?

This should hopefully do the trick:

/**
 * Append the image categories to the current image class.
 *
 * @see http://wordpress.stackexchange.com/a/156576/26350
 */

add_filter( 'get_image_tag_class', 
    function( $class, $id, $align, $size )
    {
        foreach( (array) get_the_category( $id ) as $cat ) 
        { 
            $class .= ' category-' . $cat->slug; 
        }
        return $class;
    }
, 10, 4 );

Testing (WP 3.9.1):

If we set the image categories as (for example):

rolling-stones, steel-wheels-tour, wembley

Screenshot:

image categories

and then insert the image into the post, we get the extra classes as expected:

category-rolling-stones category-steel-wheels-tour category-wembley

Screenshot:

html

Leave a Comment