03 November 2010 (age 20) Web

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

Kim Norvard 4 March 2011, 17:37

Combined with this:<br>”,wp_list_categories(‘title_li=&amp;echo=0&amp;depth=1&amp;style=none’));<br>$cat_n = count($cats) - 1;<br>for ($i=0;$i&lt;$cat_n;$i++):<br>if ($i&lt;$cat_n/2):<br>$cat_left = $cat_left.’&lt;li&gt;’.$cats[$i].’&lt;/li&gt;’;<br>elseif ($i&gt;=$cat_n/2):<br>$cat_right = $cat_right.’&lt;li&gt;’.$cats[$i].’&lt;/li&gt;’;<br>endif;<br>endfor;<br>?&gt;<br>&lt;ul class=”left”&gt;

&lt;/ul&gt;<br>&lt;ul class=”right”&gt;

&lt;/ul&gt;

It’s not showing the intended columns. Got solution?

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

Comments are closed.