Support » Plugins » Hacks » How to add classes to images based on their categories?

  • Resolved heytricia

    (@tendigit)


    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;
    }
    add_filter('get_image_tag_class','add_image_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;
    }
    add_filter('get_image_tag_class','ug_add_image_class');

    but no love…

    Help? Ideas? Please? and Happy Friday!

Viewing 1 replies (of 1 total)
  • Thread Starter heytricia

    (@tendigit)

    Much thanks to birgire at the referenced url for the solution:

    /**
     * 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 );
Viewing 1 replies (of 1 total)
  • The topic ‘How to add classes to images based on their categories?’ is closed to new replies.