Add taxonomy ID to Menu Class – WordPress

This snippet will let you add your custom taxonomy ID to your menu classes.

A somewhat typical WordPress menu classes would look like this:

<li class="menu-item menu-item-type-taxonomy menu-item-object-client menu-item-196">...</li>

I've created a custom menu from the WordPress admin > Appearance > Menus. Then added the custom taxonomy items:

custom taxonomy wordpress

Say we want to that custom taxonomy (client) and it's ID to the menu item classes. The result we want should look like this:

<li class="menu-item menu-item-type-taxonomy menu-item-object-client menu-item-196 client-16">...</li>

See that we've added client-16 at the end? This can be very useful to style certain menu items or play with jQuery selectors.

Now, here's the snippet you have to add to your functions.php file

function wpa_category_nav_class( $classes, $item ){
    if( 'client' == $item->object ){ // change client for your own custom taxonomy
        $classes[] = 'client-' . $item->object_id; // use your own custom taxonomy here as well
    }
    return $classes;
}
add_filter( 'nav_menu_css_class', 'wpa_category_nav_class', 10, 2 );

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
2 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*