1

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?

2

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.

  • Worked perfectly. Many thanks! Though @mrwweb makes a good point. I researched to see if I could use more than one value in the rel attr, but didn't know it was meant only for links. I may have to think through this approach. I've seen it used so many ways, and the w3c validator can be antiquated - so I'm used to ignoring any rel related errors. – heytricia Aug 16 '14 at 0:10
1

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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.