I’m writing a customised walker class for wp_nav_menu and want to be able to specify if an li contains a submenu. So I want my markup to be:
<li class="has_children [other-wordpress-classes]">
<a class="parent-link">Some item</a>
<ul class="sub-menu">
I know how to add and remove the classes fine, I just cant find anything to tell me if the current item has children items.
Any ideas?
Thanks in advance.
start_el()
should get this information in its$args
parameter, but it appears WordPress only fills this in if$args
is an array, while for the custom navigation menus it is an object. This is reported in a Trac ticket. But no problem, you can fill this in yourself, if you also override thedisplay_element()
method in your custom walker (because this is the easiest place to access the child element array):Update: As of WordPress 3.7 (October 2013), CSS classes have been added to indicate child menu items and pages in theme menus â no need to use a custom walker as it’s taken care of in WordPress core.
The CSS classes are named
menu-item-has-children
andpage_item_has_children
.For a complete solution for anybody in a hurry (credit to Jan Fabry’s previous answer), see the full implementation below.
Output the navigation in your theme’s template:
Then, include the following in your theme’s
functions.php
:The resulting HTML output will resemble the following:
For more information on using WordPress’ walker class, see Understanding the Walker Class.
Enjoy!
This function is exactly what you want to have. It also shows you a pretty effective way to modify nav menu items. Furthermore you can open it for more advanced (eg. child theme) functions via the item-filter:
And yes, there’s – in nearly every case – no need for a custom walker.
if you want to make drop down, you can do it with css only.
make custom nav in WP with children, WordPress automatically assigns class .sub-menu to child ul. Try this CSS
You may want to add some jQuery to spice it up a little, but this should give you a working drop down menu.