I am displaying the categories of post through the_category ();, and I would like to customize the text, such as changing the color, font-size...

This is my code:

<span class="post_info"><?php the_category (', '); ?> </span>

This code only prints the <a> tag, without class and without ID.

I looked in the codex of the_category and get_the_category something about the addition of classes, but found nothing on.

So, how I can add certain class to this element?
How I can add a class to display a category?

---------------------------------- UPDATE ------------------------------

This code makes that I want:

function add_class_to_category( $thelist, $separator, $parents){
    $class_to_add = 'custom-slug';
    return str_replace('<a href="',  '<a class="'. $class_to_add. '" href="', $thelist);

add_filter('the_category', __NAMESPACE__ . '\\add_class_to_category',10,3);

Instead of using the_category, I would just build the category links manually and add the category slug as the class name. Something like this:

<span class="post_into">
        $thelist = '';
        $i = 0;
        foreach( get_the_category() as $category ) {
            if ( 0 < $i ) $thelist .= ', ';
            $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" class="' . $category->slug . '">' . $category->name.'</a>';
        echo $thelist;
  • The aim of entering the class is just to modify ALL of them at once. Using a slug I would have to modify one by one /: – Zkk Aug 3 '16 at 1:13
  • Why did you need a class at all then if you're going to style them all the same? Why not just target ".post_info a" – Nate Allen Aug 3 '16 at 4:28
  • Because of escalability and inside of <span class="post_info"> I've others tags <a>. – Zkk Aug 3 '16 at 15:43

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.