最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How can I add a class to displays a category?

programmeradmin0浏览0评论

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

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);
Share Improve this question edited Aug 3, 2016 at 1:15 Zkk asked Aug 2, 2016 at 0:19 ZkkZkk 1751 gold badge4 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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">
    <?php
        $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>';
            $i++;
        }
        echo $thelist;
    ?>
</span>
发布评论

评论列表(0)

  1. 暂无评论