1

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.

1 Answer 1

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!

3
  • Thank you! What if I would like to link to the categories and to use some of the wp_list_categories functions? Like hide_empty?
    – Cody
    Sep 26, 2012 at 16:58
  • It's pretty easy. Just have a look at those two links in the answer. For example, on the get_the_category Codex page, they have a code sample for getting the link (using get_category_link($category->term_id )). And empty categories should be hidden by default (because the $args parameter for get_categories() has an element called hide_empty.
    – Jared Cobb
    Sep 26, 2012 at 17:15
  • @ Jacob Cobb - thanks again - and sorry, I somehow missed the link!
    – Cody
    Sep 26, 2012 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.