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.
Add Custom Text to a Specific Menu (Easy Way) Simply go to the Appearance » Menus page and add a custom link with # sign as the URL, and the text you want to display as your Link Text. Click on the Add to Menu button to continue. WordPress will add your custom text as a menu item in the left column.
To do this go to Appearance >Menus and start creating a new menu. Give the menu the title “Secondary Menu”, select “My Custom Menu” for a location and then hit the “Create Menu” button. Finally add some items to the menu (for example Menu item 1, Menu item 2, Menu item 3) and then save the menu.
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-includes\nav-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 functions start_el
and end_el
are used to build the menu-items. Functions start_lvl
and end_lvl
are for nesting menus. In this approach we'll be mainly using start_el
and end_el
.
In your functions.php
create a class, to extend Walker_Nav_Menu
with pretty similar methods to the parent class:
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
// Copy all the start_el code from source, and modify
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
// Copy all the end_el code from source, and modify
}
}
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 include start_lvl
and end_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:
wp_nav_menu(array(
'theme_location' => 'main',
'container' => false,
'menu_id' => 'nav',
'depth' => 1,
// This one is the important part:
'walker' => new Custom_Walker_Nav_Menu
));
WordPress will use your custom class and functions, so that you can modify what code is output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With