Only append custom classes to nav menu items

I was reviewing this extremely helpful post on cleaning up WP-generated classes and ids from the nav menu, and found RevelationTravis’s option– see code below– to be particularly good as a way to effectively “whitelist” certain menu classes. I’m wondering, however, if there’s a way to retain the custom nav menu classes specified via the WP menu admin panel– i.e. “CSS Classes (Optional)”– without having to list them explicitly by name?

<?php
//Deletes all CSS classes and id's, except for those listed in the array below
function custom_wp_nav_menu($var) {
    return is_array($var) ? array_intersect($var, array(
        //List of allowed menu classes
        'current_page_item',
        'current_page_parent',
        'current_page_ancestor',
        'first',
        'last',
        'vertical',
        'horizontal'
        )
    ) : '';
}
add_filter('nav_menu_css_class', 'custom_wp_nav_menu');
add_filter('nav_menu_item_id', 'custom_wp_nav_menu');
add_filter('page_css_class', 'custom_wp_nav_menu');

//Replaces "current-menu-item" with "active"
function current_to_active($text){
    $replace = array(
        //List of menu item classes that should be changed to "active"
        'current_page_item' => 'active',
        'current_page_parent' => 'active',
        'current_page_ancestor' => 'active',
    );
    $text = str_replace(array_keys($replace), $replace, $text);
        return $text;
    }
add_filter ('wp_nav_menu','current_to_active');

//Deletes empty classes and removes the sub menu class
function strip_empty_classes($menu) {
    $menu = preg_replace('/ class=""| class="sub-menu"https://wordpress.stackexchange.com/",'',$menu);
    return $menu;
}
add_filter ('wp_nav_menu','strip_empty_classes');
?>

Thank you for any assistance here.

1 Answer
1

Yes, they’re stored as metadata '_menu_item_classes' for each menu item so eg (updated to use separate function)

function custom_wp_nav_menu_css_class( $classes, $item, $args, $depth ) {
    $whitelist = array(
        //List of allowed menu classes
        'current_page_item',
        'current_page_parent',
        'current_page_ancestor',
        'first',
        'last',
        'vertical',
        'horizontal'
    );
    // Note array containing empty entry always created for menu item meta so filter out.
    if ( $optional = array_filter( get_post_meta( $item->ID, '_menu_item_classes', true ) ) ) {
        $whitelist = array_merge( $whitelist, $optional );
    }
    return array_intersect( $classes, $whitelist );
}
add_filter( 'nav_menu_css_class', 'custom_wp_nav_menu_css_class', 10, 4 );

Leave a Comment