I'm using array_intersect() to remove all classes from my Wordpress menu-items, except the ones listed. Then I'm using str_replace to rename the classes. This works, but it feels sloppy. Is there a more efficient way of doing this?
function my_nav_menu_css_class( $classes ) {
$classes = array_intersect( $classes, array(
'current-menu-ancestor',
'menu-item-has-children',
'current-menu-item',
));
$classes = str_replace( 'current-menu-ancestor', 'ancestor', $classes );
$classes = str_replace( 'menu-item-has-children', 'children', $classes );
$classes = str_replace( 'current-menu-item', 'item', $classes );
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_nav_menu_css_class' );
Note: the above classes are all conditional; they will only appear if the menu is active or is a dropdown menu. In other words, trying this didn't work:
$rename_classes = array(
'ancestor',
'children',
'item',
);
return str_replace( $classes, $rename_classes, $classes );
In this case .current-menu-item is supposed to be replaced with .item but is replaced with .ancestor instead (because it came first in the array). So that's no good. Any better solutions?