I need to be able to: 1.) assign categories to images and 2.) add classes to all images that correspond to their assigned categories.

I was able to add categories to images with the following:

function ug_add_categories_to_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
add_action( 'init' , 'ug_add_categories_to_attachments' );

And I found a function to add a class to images as so:

function add_image_class($class){
    $class .= ' additional-class';
    return $class;

But I'm not advanced enough with php to take it much further. I tried this

function ug_add_image_class($class){
    foreach(get_the_category() as $cat) { $class .= ' category-'.$cat->slug; };
    return $class;

but no love...

Help? Ideas? Please? and Happy Friday!

1 Answer 1


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


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



  • 2
    Worked perfectly! Thanks much... you're the official 'hero of the day!'
    – heytricia
    Aug 4, 2014 at 19:43
  • @heytricia Great to hear it worked for you, I will check out "Hero of the Day" by Metallica on their 1996 album Load and enjoy it for the rest of the day, thanks ;-)
    – birgire
    Aug 4, 2014 at 19:48
  • So how hard would it be to modify this and add the categories to a rel attribute? I'm thinking this would be a better approach to image filtering.
    – heytricia
    Aug 14, 2014 at 18:00
  • 1
    @birgire Great band, great song, and great answer Aug 14, 2014 at 18:29
  • 1
    @PieterGoosen thanks - WordPress is much better with music ;-)
    – birgire
    Aug 14, 2014 at 18:53

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.