How to add style to category link?

<h1><?php the_category(' &bull; '); ?> ร‚ยป <a href="<?php the_permalink(); ?>" class="my-title-class"><?php the_title(); ?></a></h1>

How to add class="my-category-class" to the links, produces by the_category function?

Related posts

Leave a Reply

3 comments

  1. You can use the_category filter to hook a callback function like this:

    add_filter('the_category','add_class_to_category',10,3);
    
    function add_class_to_category( $thelist, $separator, $parents){
        $class_to_add = 'my-category-class';
        return str_replace('<a href="', '<a class="' . $class_to_add . '" href="', $thelist);
    }
    
  2. Pick your choice:

    • style categories by already existing CSS definition: .post-categories a {YOUR_STYLE_HERE};
    • use jQuery to add your class: $("link-categories a").addClass("my-category-class");;
    • write your own function to echo categories with your own classes/attributes.
  3. As a beginner I would try creating my function, that I would call instead of the_category();

    function my_category_func($sep, $classname)
        {
            $output = null;
            $output = '<div class="$classname">'.the_category( $sep ).'</div>';
            return $output;
        }
    

    I believe this could be done more professionally, including all the variables, but I’d go this way for starters ๐Ÿ˜‰