Highlight the current category for single posts in WordPress
When you browse a category in WordPress, a current-cat
class is added to the category’s list item in the wp_list_categories
menu. This is really useful for styling your menu so readers have a visual cue of where they are in your blog.
But when viewing an individual post, the current-cat
class doesn’t get generated. To generate it when your visitors are reading a single post, insert the following code in your theme’s functions.php file.
// Generate the current-cat class when viewing single posts class singlePostCurrentCat { function wp_list_categories ($text) { global $post; if (is_singular()) { $categories = wp_get_post_categories($post->ID); foreach ($categories as $category_id) { $category = get_category($category_id); $text = preg_replace( "/class=\"(.*)\"><a ([^<>]*)>$category->name<\/a>/", ' class="$1 current-cat"><a $2>' . $category->name . '</a>', $text); } } return $text; } } add_filter('wp_list_categories', array('singlePostCurrentCat','wp_list_categories'));
(Adapted from Kahi’s Highlight Used Categories plugin.)
Sam Nabi
Comments
Ryan Paonessa 11 December 2010, 02:10
awesome. thanks man
Kim Norvard 4 March 2011, 17:37
Combined with this:<br>”,wp_list_categories(‘title_li=&echo=0&depth=1&style=none’));<br>$cat_n = count($cats) - 1;<br>for ($i=0;$i<$cat_n;$i++):<br>if ($i<$cat_n/2):<br>$cat_left = $cat_left.’<li>’.$cats[$i].’</li>’;<br>elseif ($i>=$cat_n/2):<br>$cat_right = $cat_right.’<li>’.$cats[$i].’</li>’;<br>endif;<br>endfor;<br>?><br><ul class=”left”>
</ul><br><ul class=”right”>
</ul>
It’s not showing the intended columns. Got solution?
Stephen Miller 12 July 2012, 18:47
awesome, saved me a lot of time, thanks man!
Andrew M Rivera 20 November 2013, 21:50
Thank you so much!
Trần Đăng 1 June 2017, 22:09
Great. Thank you very much. Thanks to you, I have dealt with my problem :D
Post a comment