WordPress: Adding the category as text – not link

I want to add a ribbon on my posts on the front page, which shows the posts category.

I can add it as text like this (I use the Imbalance theme by WPShower):

Read More
<?php imbalance2_posted_in(); ?>

But how can I just write the Category Name, without markup so I can use it in classes and such?

Thank you in advance.

Related posts

Leave a Reply

2 comments

  1. You can get the category of every post with get_the_category(). Below is shown how to get the category of the current post.

    global $post;
    $category = get_the_category( $post->ID ); //OR SOME OTHER ID, DEPENDING ON WHAT YOU WANT
    $category_name = $category->name; //GETS THE ORIGINAL NAME, INCLUDING WHITESPACES
    $category_slug = $category->slug; //GETS THE SLUG, WHICH WILL BE BETTER TO USE IN CLASSNAMES
    

    EDIT

    <?php 
        global $post;
        $category = get_the_category( $post->ID ); 
    ?>
    
    <div class="box <?php echo($category->slug); ?>"></div>
    
  2. You can use post_class() to generate a few class names including one for each category.

    If you want to do it manually, you can get information on the categories using get_the_category() and put the class names together yourself.