I am trying to design a button in the sidebar which is related to the post displayed. The button is basically a “other news in CAT1”. i have this piece of code:
<div id="pagine">
<?php
$category = get_the_category();
if($category[0]){
echo '<a href="'.get_category_link($category[0]->term_id ).'"><div id="pagine"><ul><li>News su '.$category[0]->cat_name.'</li></ul></div></a>';
}
?>
</div>
which unfortunately displays the wrong category. Can please anybody tell me how to do it. It shouldn’t be that difficult, i just started with wordpress.
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.