0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Point taken. But I'm still curious if there is a better way of writing this, in case I ever have to do something else like this.
I would just foreach through $classes and build a $newClasses array with all the same items, making any necessary modifications on the way. Again, keep it simple. Don't try to do anything fancy.
True words. I gotta be less perfectionist and more practical.
1

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

1 Comment

Ya I had a feeling I wasn't doing this the best way, I should make better use of loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.