Wordpress menu as category list

in Tips and Tricks, WordPress

Mark active category in single page(wordpress)

I think my post title is not clear and it’s really not possible to tell every thing in just a simple post title :P. Ok, I am taking about:
1. WordPress
2. Category menu in wordpress using wp_list_categories()

If you make a wordpress menu using category listing in wordpress then the html code will be like this

Wordpress menu as category list

Wordpress menu as category list(click image to see full)

In the above picture , you see same thing twice , firt one
1. when we are not in any category page(category archive page)
2. when we are in a category archive page , the active category list gets a extra class name “current-cat”
So my post is about when we are browsing any single post how can we mark the the category as “current-cat” that post belongs to so that the active category list can be styled using css.

So to do that I got a plugin (please check here) but i am not happy as the plugin put active class for anchor tag… Please check the plugin code.

[code language=”php”]
function show_active_category($text) {

global $post;

if( is_single() ) {

$categories = wp_get_post_categories($post->ID);

foreach( $categories as $catid ) {
$cat = get_category($catid);
if(preg_match(‘#>’ . $cat->name . ‘</a>#’, $text)) {
$text = str_replace(‘>’ . $cat->name . ‘</a>’, ‘ class="active_category">’ . $cat->name . ‘</a>’, $text);
}
}

}

return $text;

}

add_filter(‘wp_list_categories’, ‘show_active_category’);
[/code]

and here is my version

[code language=”php”]
function show_active_category($text) {

global $post;

if( is_single() ) {

$categories = wp_get_post_categories($post->ID);

foreach( $categories as $cat )
{
//var_dump($cat);
if(preg_match(‘#
<li class="cat-item cat-item-‘.$cat.’">#’, $text))
{
$text = str_replace(‘</li>
<li class="cat-item cat-item-‘.$cat.’">’, ‘</li>
<li class="cat-item cat-item-‘.$cat.’ current-cat">’, $text);

}
}

}

return $text;

}

add_filter(‘wp_list_categories’, ‘show_active_category’);
[/code]

you can put the above your in your functions.php file and no need to install an extra plugin.

That’s it.

  1. Hi, thanks for the snippet, Used it, but it needs a little fixing

    The problem is that if the current category is the first category it won't get "current-cat". the reason is that you called to the li close tag (line 15 in your code) or the line break (line 12 in your code).

    But for the first category the is no li close tag before it – hence – your first category won't get the "current-cat".

    Just fix that, and you are ready to go 🙂

  2. Very useful article.

    Dear Manchu Da,

    Please write about dragging dropping and collapsing wordpress sidebar wadget like your blog.

Comments are closed.