Adding category ID or slug to WP Nav Menu

Is it possible to add the id or slug of a category in the output of wp_nav_menu menu’s?

For example, the standard output of wp_nav_menu is:

Read More
<div class="menu-header">
    <ul id="menu-categorieen" class="menu">
        <li id="menu-item-4353" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-4353"><a href="http://domain/">Home</a></li>
        <li id="menu-item-1034" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1034"><a href="http://domain/category/category_1/">Category 1</a></li>
        <li id="menu-item-1039" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1039"><a href="http://domain/category/category_2/">Category 2</a></li>
        <li id="menu-item-1032" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1032"><a href="http://domain/category/category_3/">Category 3</a></li>
    </ul>
</div>

I’m wondering if it is possible to add the category slug to the css class for that <li>, like so:

<div class="menu-header">
    <ul id="menu-categorieen" class="menu">
        <li id="menu-item-4353" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-4353"><a href="http://domain/">Home</a></li>
        <li id="menu-item-1034" class="menu-category-1 menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1034"><a href="http://domain/category/category_1/">Category 1</a></li>
        <li id="menu-item-1039" class="menu-category-2 menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1039"><a href="http://domain/category/category_2/">Category 2</a></li>
        <li id="menu-item-1032" class="menu-category-3 menu-item menu-item-type-taxonomy menu-item-object-category menu-item-1032"><a href="http://domain/category/category_3/">Category 3</a></li>
    </ul>
</div>

Related posts

Leave a Reply

1 comment

  1. Use the nav_menu_css_class filter to add classes to wp_nav_menu output.

    Add ID (no additional query needed):

    function wpa_category_nav_class( $classes, $item ){
        if( 'category' == $item->object ){
            $classes[] = 'menu-category-' . $item->object_id;
        }
        return $classes;
    }
    add_filter( 'nav_menu_css_class', 'wpa_category_nav_class', 10, 2 );
    

    Add slug (loads category object via get_category):

    function wpa_category_nav_class( $classes, $item ){
        if( 'category' == $item->object ){
            $category = get_category( $item->object_id );
            $classes[] = 'menu-' . $category->slug;
        }
        return $classes;
    }
    add_filter( 'nav_menu_css_class', 'wpa_category_nav_class', 10, 2 );