Tech Notes: Adding a class to parent menu items in WordPress

WordPress’s navigation menus were such a great addition when they arrived. But they are sometimes lacking in specifics.
WordPress puts CSS classes like current_page_item, current_menu_item, current_page_parent and so on on the menu items so that you can highlight items.
But I had a two-level navigation menu where I wanted to apply different styles to an item only if it had a sub-menu. Adding a class to a parent menu item is not so easy.
As always, I’m indebted to the WordPress community who got me some of the way. I’ve forgotten my sources for the solution to this particular puzzle, but I was not without the usual help. Here’s my summing up of how to add a class to a parent menu item.
I’m not sure it’s the best solution. It’s inefficient because it runs a WordPress query for each menu item. A better way would be to set some meta data on the menu item when the item is saved and use that meta data in the filter. Or you could keep a list in a transient or something. So there are better ways. But it’ll do for now.
/*
* This adds a "dropdown" class to menus
*/
function oikos_add_menu_parent_classes( $classes, $item, $args ) {
$children = get_posts( array(
'meta_query' => array (
array(
'key' => '_menu_item_menu_item_parent',
'value' => $item->ID )
),
'post_type' => $item->post_type ) );
if (count($children) > 0) {
array_push($classes,'dropdown'); // add the class .dropdown to the current menu item
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'oikos_add_menu_parent_classes', 10, 3 );