Search code examples
phphtmlcsscategoriestaxonomy

Different background color on each categories


How can I display my categories in different background color using a custom post? I like to echo the slug name from my taxonomy to become the class attributes of span and style it in css. but I can't able to echo the slug name and I can't display the category name at the same time.

    <?php $post_terms = get_the_terms(); ?>
        <span class="<?php echo $post_terms[0]->slug; ?>">
            Categories: <?php echo $post_terms[0]->cat_name; ?>
        </span>

can you show me what is the right code?


Solution

  • you can achieve that using this codes;

        <?php $category = get_the_terms( $post->ID, 'your_taxonomy_cat_name' ); ?> 
            <span class="post-category-color-text <?php echo $category[0]->slug; ?>">
            Categories: <?php  foreach ( $category as $cat){ echo $cat->name;}?>
        </span>
    

    I hope this code will help you. happy coding