WordPress wp_nav_menu output class when menu item has children
I recently wanted to insert a class for the case where a menu item has children in WordPress. There doesn’t appear to be any option to do this in wp_nav_menu function, so I started doing some research.
I found out from this article how to add a ‘last-menu-item’ css class.
This doesn’t quite work for what I wanted though, because the returned data object from WordPress doesn’t tell you if the current node has children.
So, I used a walker object instead (there’s a good article on their usage here) and then used the theory behind the first article to achieve my objective. Nice.
<?php
class TopnavWalker extends Walker_Nav_Menu
{
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$intPos = strripos($output,'menu-item');
$output = sprintf("%s has-children %s",
substr($output,0,$intPos),
substr($output,$intPos,strlen($output))
);
$output .= "\n$indent<ul class=\"sub-menu\">\n";
}
}
?>
