Why do Custom Nav Menus generate so many classes on list items? Can I manage this somehow?

I’m going against the majority on this one 🙂

Yes, it can be a good idea to strip it down. Personally I’m keeping only the current-xxx type classes and replacing them with active, and active-parent (for active parent or ancestor items).

Why?

  • around the web, active has became the standard class for active menu items (on top of that WP has inconsistent class naming conventions between its’ own class names).
  • you get to write less CSS rules; the bandwidth that you save might not be much, but it certainly makes the CSS file more readable

Updated code:

// for custom menus 
add_filter('nav_menu_css_class', 'normalize_wp_classes', 10, 2);

// for the page menu fallback (wp_list_pages)
add_filter('page_css_class', 'normalize_wp_classes', 10, 2);

/**
 * @param  $classes array
 * @param  $item object
 * @return array
 */
function normalize_wp_classes(array $classes, $item = null){

  // old classes to be replaced with 'active'
  $replacements = array(
    'current-menu-item',
    'current-menu-parent',
    'current-menu-ancestor',
    'current_page_item',
    'current_page_parent',
    'current_page_ancestor',
  );

  // if any of the classes above are present,
  // return an array with a single class ('active')
  return array_intersect($replacements, $classes) ? array('active') : array();
}

Update: For anyone using this code, the active-parent class is no longer required (unless you still need IE 6 support). Using the child selector (>) you can effectively style the active parent and active child any way you want.

Leave a Comment