I’m familiar with WordPress and using the WordPress menu system. But I’m looking for a way to add custom HTML to wp_nav_menu()
.
I’m trying to create a menu like this:
Notice how the drop down menu under products contains an image and a link. I’d like to re-create this. I’ve looked at a few plugins, but would rather code it.
I don’t mind hard coding the image and link, but I’d like to keep the flexibility of using WordPress to manage the menus.
The way WordPress goes through the menu pages to display the items, is using a walker object. In this case the specific class for this object is called Walker_Nav_Menu. You can find it in
wp-includesnav-menu-template.php
.The
Walker_Nav_Menu
is a pretty simple class. You are able to see, how the links and the menu structure are built there. The functionsstart_el
andend_el
are used to build the menu-items. Functionsstart_lvl
andend_lvl
are for nesting menus. In this approach we’ll be mainly usingstart_el
andend_el
.In your
functions.php
create a class, to extendWalker_Nav_Menu
with pretty similar methods to the parent class:In those functions, the
$item
is your menu-item, with which you can query additional contents according to the current menu-item, if you want to. Note that I didn’t includestart_lvl
andend_lvl
, but that doesn’t matter, since your class will automatically inherit the parent classes methods, if not overwritten.Then, in your theme files, you can call wp_nav_menu like this:
WordPress will use your custom class and functions, so that you can modify what code is output.