Blog / WordPress/ How to Remove Extra CSS Classes from WordPress Navigation Menus

How to Remove Extra CSS Classes from WordPress Navigation Menus

WordPress如何移除菜单导航中自带的多余Class类名

If you have successfully added multiple custom menus in the WordPress admin and called them on the front end, you might notice the navigation output includes many default CSS classes. This article explains how to clean up those extra class names.

Solution: Filter Navigation Menu Classes

The core method is to use WordPress filter hooks. Add the following PHP code to your theme's functions.php file:

// Remove extra classes from nav menus
add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1);
add_filter('nav_menu_item_id', 'my_css_attributes_filter', 100, 1);
add_filter('page_css_class', 'my_css_attributes_filter', 100, 1);
function my_css_attributes_filter($var) {
    return is_array($var) ? array_intersect($var, array('current-menu-item','current-post-ancestor','current-menu-ancestor','current-menu-parent')) : '';
}

How It Works

This code hooks into three filters that control the CSS classes and IDs output for menu items. The my_css_attributes_filter function checks if the input is an array. If it is, it keeps only the specified 'current' classes (which are useful for styling the active page). All other classes are removed. If the input is not an array (like an ID string), it returns an empty string.

Usage Instructions

  1. Copy the code block above.
  2. Paste it into your active theme's functions.php file.
  3. Save the file and refresh your website's front end.
  4. Inspect your navigation menu's HTML; the extra classes should now be gone, leaving only the essential 'current' state classes.

This results in cleaner, more manageable HTML output for your menus.