3

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

anybody got any ideas?

thanks!

5

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 );
}
  • +1 Nice one. Now if I could just get the current-menu-item back! – N2Mystic Oct 6 '11 at 14:08
  • @N2Mystic well you only need to check incoming $classes for it and keep it, instead of returning retrieved array only. – Rarst Oct 6 '11 at 14:13
1

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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