As seen on the right, you can highlight the currently visited category in WordPress – which is not a standard thing. You have to add some code to your template. Here’s what I did.
The WordPress function wp_list_categories takes a number of parameters that make showing the current category possible. Normally, the function is already in place in your sidebar.php file. I’m using a custom sidebar for the blog section, but I’ll not go into how that works now. If you’re going to edit your sidebar.php file, it’s best practice to copy it into your theme folder, so when the next WordPress update comes around, your work doesn’t get overwritten.
What the function does is retrieve a list of categories, and echos them pre-wrapped as links in <li> tags. So you could use the function anywhere you like, but wrap it in an <ul> tag. My code looks like this:
<ul>
<?php
//get this posts category object
$thisCat = get_the_category();
if(!is_home()){
$currCatId = $thisCat[0]->cat_ID;
//no title, no counts, show subcats,
order by termgroup (edit # in DB!), hide cat "Tests", show currentcat
wp_list_categories('title_li=&show_count=0&hierarchical=1
&orderby=term_group&exclude=8¤t_category='.$currCatId);
}else{
wp_list_categories('title_li=&show_count=0&hierarchical=1
&orderby=term_group&exclude=8');
}
?>
</ul>
I already know that this code is not executed on a page but only in the blog section, so there is no need to add checks for pages in the if statement. Read it as if it was preceded by this:
if(is_home() || is_category() || is_archive() || is_search() || is_single())
So, what this does is: if the current page is not the blog home, but is a blog category, an archive list page, a search page or a single blog post, figure out what the page’s category ID is, get the list of categories, and give the <li> tag for the current one a class of “current_cat”. Then you can style this list item in whatever way you want.
There’s a few other non-standard things I’m doing here: for one, I exclude a category from showing up in the list – my “Tests” category is public, but does not need to be prominently visible. I use the parameter “orderby” to order the categories by a term group ID number that I edited in the database – quite non-standard, or rather more like a blatant mis-use of features, and not useful for managing a large number of categories, but it works for now. It’s a wonderful source of wisdom, that WordPress Codex!
2 Comments
Nice fix – showing the current category makes a lot of sense. Will try to paste your code into my site and see how that goes.
Thank you so much! This is exactly what I needed.