Hello Developers, Greetings of the day!!
Today I am going to show you how to add category slug as class in wp nav menu items.
When we have added category in wp nav menu then by default it did not show category slug as class.
For example, we have added ” blog ” category in wp nav menu but it did not show category slug as class in wp nav menu item.
Please check below screenshot.
So, you have to add below function in your functions.php file.
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 );
After added this function you can see category slug in wp nav menu items as class.
Please see below screenshot.
If you want to add category id in wp nav menu item the you can use below function.
function wpa_category_nav_class( $classes, $item ){ if( 'category' == $item->object ){ $classes[] = 'catagory-menu-' . $item->object_id; } return $classes; } add_filter( 'nav_menu_css_class', 'wpa_category_nav_class', 10, 2 );
Thanks and keep visiting 🙂