How to add a rel attribute to images that contains their categories?

I’ve added categories to images, so that I can use them to filter images within a portfolio page. Now I’m thinking I need to add the rel attribute to each image that contains its assigned categories. Is this the right approach? If so, how do I add add rel with the applicable categories?

Solutions Collecting From Web of "How to add a rel attribute to images that contains their categories?"

This should work for the rel attribute:

/**
 * Create a rel attribute from the image categories
 *
 * @see http://wordpress.stackexchange.com/a/158024/26350
 */

add_filter( 'get_image_tag', 
    function( $html, $id )
    {
        $rel = array();

        foreach( (array) get_the_category( $id ) as $cat ) 
        { 
            $rel[] = $cat->slug; 
        }

        return str_ireplace( 
            '<img ', 
            sprintf( '<img rel="%s" ', join( ' ', $rel ) ),
            $html
        );
    }
, 10, 2 );

where we use the get_image_tag filter to modify the inserted image HTML.

Ps: I just tested this successfully on my WordPress 3.9.2 install, where I used the following code snippet:

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

to activate the categories for attachments.

I ended up modifying slightly to use data-filter instead of rel. Works perfectly and complies with standards.

add_filter( 'get_image_tag', 
    function( $html, $id )
    {
        $dataFilter = array();

        foreach( (array) get_the_category( $id ) as $cat ) 
        { 
            $dataFilter[] = $cat->slug; 
        }

        return str_ireplace( 
            '<img ', 
            sprintf( '<img data-filter="%s" ', join( ' ', $dataFilter ) ),
            $html
        );
    }
, 10, 2 );