Reputation: 2332
I'm using array_intersect()
to remove all class
es 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?
Upvotes: 0
Views: 94
Reputation: 224
am i reading this right, you are doing something N times (here 3)? and the end result is the list of classes that exist in the $classes you pass in? if this is the case use a foreach loop. and in_array()
sorry i if i got this wrong. but doing something N times indicates using a loop
Upvotes: 1
Reputation: 33369
You should update your CSS to use ".current-menu-item" instead.
Anything you do in PHP will make the website slightly slower to load, and potentially buggy.
The best code is no code at all, only write the minimum amount you need to solve a given problem. Less work for you, less bugs and faster execution for the end user. That's a win all around.
Upvotes: 1