Filter out built-in wp_nav_menu classes but keep custom class

Im trying to remove / filter our all the classes from the wp_nav_menu, EXCEPT the custom ones that i insert (in the “CSS Classes (optional)” field) when creating the menu in the admin.

I found a function that removes EVERYTHING, but thats no good

Read More

anybody got any ideas?

thanks!

Related posts

Leave a Reply

2 comments

  1. One of the darker corners of the code. 🙂 Here is my take:

    add_filter('nav_menu_css_class', 'discard_menu_classes', 10, 2);
    
    function discard_menu_classes($classes, $item) {
    
        return (array)get_post_meta( $item->ID, '_menu_item_classes', true );
    }
    
  2. I’m trying to answer.

    The function that responsible to generate classes for menu items is _wp_menu_item_classes_by_context in the file wp-includes/nav-menu-template.php. You can dig there to see what classes it generate, so you can strip it out in nav_menu_css_class filter.

    I found that every classes that automatically generated started with menu-item class. So, in the filter I loop the classes array until found that class.

    This is my code:

    function my_nav_menu_css_class($classes) {
        $custom_classes = array();
        foreach($classes as $class) {
            if($class=='menu-item') return $custom_classes;
            $custom_classes[] = $class;
        }
    }
    add_filter('nav_menu_css_class', 'my_nav_menu_css_class');