Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to remove all menu-item classes (except for .current-menu-{item/parent/ancestor} and .menu-item-has-children)

function custom_nav_menu_css_class($classes) {
    $classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes);
    return $classes;
}
add_filter('nav_menu_css_class', 'custom_nav_menu_css_class');

This almost does the job, except it removes .menu-item-has-children? Any idea what I should change, to exclude it from being removed?

(P.S. I'd rather not use a custom walker...)

share|improve this question

1 Answer 1

up vote 1 down vote accepted

You could work with a white-list and replace the regular expression with something more readable:

add_filter( 'nav_menu_css_class', function( $classes ) {
    $allowed = array(
        'menu-item-has-children',
        'current-menu-item'
    );
    $output      = array();

    foreach ( $classes as $class )
    {
        if ( in_array( $class, $allowed ) )
            $output[] = $class;
    }

    return $output;
});

That would make it easier to maintain the white-list too.

share|improve this answer
    
Good idea! But I'm getting 'explode() expects parameter 2 to be string' –  Lisa Feb 8 at 20:59
    
@Lisa My bad. Hastily written code without even testing it. :) I made an update to my answer. –  toscho Feb 8 at 21:01
    
Thanks this works! Though I changed it to return $output because it kept saying join() passed invalid arguments. Will changing this cause a problem tho? –  Lisa Feb 8 at 21:25
    
@Lisa That was a leftover from my last edit. return $output; is correct, I fixed that in my answer. –  toscho Feb 8 at 21:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.