Removing all classes from nav_menu except current-menu-item and current-menu-parent

Thanks to Rarst’s clever answer, I’m succesfully using these bits to remove the classes from the custom menu markup…

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

However, I do need the current-menu-item and current-menu-parent classes when I’m viewing a current page element or a child of a current-menu-item.

Is it possible to add these without all the extra classes?

1 Answer
1

Sure, you can filter out all the classes but the ones you want.

add_filter('nav_menu_css_class', 'discard_menu_classes', 10, 2);

function discard_menu_classes($classes, $item) {
    $classes = array_filter( 
        $classes, 
        create_function( '$class', 
                 'return in_array( $class, 
                      array( "current-menu-item", "current-menu-parent" ) );' )
        );
    return array_merge(
        $classes,
        (array)get_post_meta( $item->ID, '_menu_item_classes', true )
        );
    }

Leave a Comment