How to get the category of the post and link it to the archive (of the category)

One these three should do the job for you…

1. Function: the_category();

News su <?php the_category(', '); ?>

Displays as:

News su WordPress, Computers, Blogging

And if only a single category is assigned to a post, it shows up like this:

News su WordPress

2. Function: get_the_category_list();

<div id="pagine"><?php echo get_the_category_list(); ?></div>

Displays as:

<div id="pagine">
    <ul class="post-categories">
        <li>
            <a href="http://example.com/category/wordpress/" title="View all posts in Business" rel="category tag">WordPress</a>
        </li>
        <li>
            <a href="http://example.com/category/computers/" title="View all posts in Business" rel="category tag">Computers</a>
        </li>
    </ul>
</div>

And if only a single category is assigned to a post, the output would be like this:

<div id="pagine">
    <ul class="post-categories">
        <li>
            <a href="http://example.com/category/wordpress/" title="View all posts in Business" rel="category tag">WordPress</a>
        </li>
    </ul>
</div>

3. Function: single_cat_title();

If you want to show just one category (category with the lowest ID will be shown) no matter how many categories are assigned to a post, use something like this:

<div id="pagine">
    <ul>
        <li>
            <?php
                $category = get_the_category();
                echo '<a href="'.get_category_link($category[0]->cat_ID).'">News su ' . $category[0]->cat_name . '</a>';
            ?>
        </li>
    </ul>
</div>

The above code always shows one category, like this:

News su WordPress

So, given the codes (and what each does), suit them to your needs.

Leave a Comment