Giving wp_list_categories the class of the category

I am using wp_list_categories to list my categories in my menu. When the menu is generated each category is listed as a <li>-element with “cat-item[number]” as class.

Is there a way to also or instead give the <li>s the category name as the class? Just like the posts have the category name as the class.

Related posts

Leave a Reply

1 comment

  1. I would use get_categories() instead, so that you can have better control over the output of your list. And if I recall correctly, wp_list_categories calls get_categories anyway. You can use the same $args array in either function, and you should get the same categories as a result.

    Then you can simply build your own unordered list like so:

    // build category collection
    $categories = get_categories($args);
    $menu = '<ul>';
    
    // iterate through your categories
    foreach($categories as $category) {
    
        // you can also use $category->slug
        $menu .= '<li class="' . $category->name . '">' . $category->name . '</li>';
    
    }
    
    $menu .= '</ul>';
    echo $menu;
    

    Of course, you may build out as much markup to your <ul> and <li> tags as you wish (additional classes, anchors, etc).

    You may even wish to mimic all the other classes that wp_list_categories adds (just so that you stay consistent). And if you use this in multiple places, it might even be good to create your own function.

    For a complete reference of which properties are available in your $category object see the Codex.

    Hope that helps!