Wrote a little javascript and hook for a WordPress client today who wants the category of the current post highlighted (on single.php). Note that if you’d like to implement this, you’ve got to have jQuery already.
The php for category html output:
I’ve got the cat-item-0 in there because WordPress doesn’t generate something like that automatically, of course. It’s essentially just a link to the main posts page, or blog home. So after WordPress processing, the output html looks something like this:
Next, I’ve got a javascript function in the functions.js file that’s included in the head of the theme:
function highlightCurrentCategory(catid) {
jQuery('.cat-item-'+catid).addClass('current-cat');
}
When the function is run, it’s passed the ID of the category to highlight, and it adds the current-cat class to that list item.
Finally, in the functions.php file for the theme, I’ve got this php function and the add_action for the hook:
function highlightCurrentCategory() {
global $post;
if (is_single()) {
$category = get_the_category($post->ID);
echo '';
}
if (is_home()) {
echo '';
}
}
add_action('wp_footer', 'highlightCurrentCategory');
It’s using wp_footer so that it happens at the very end of the page and doesn’t slow down other things that might need to happen sooner on the page. The javascript is only printed for single-post pages and for the home page – if it’s a category page, WordPress automatically includes the current-cat class.