I’m developing a plugin and I want to insert menu items programmatically.
When my theme creates a menu, it uses this call:
wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) );
Which resulted in something like this in the HTML:
<div class="nav-menu"><ul>
<li class="current_page_item"><a href="somewhere">menu-item-1</a></li>
<li class="page_item page-item-107"><a href="somewhere-else">menu item 2</a></li>
</ul></div>
I want to be able to intercept this somehow and insert my own HTML programmatically before the closing </ul>
. How do I hook it up?
Before being printed, all the menu items get run through a filter. You can target the
wp_nav_menu_items
filter to tack things on to the menu:Or, to be more specific, you can target only the desired menu by replacing the
add_filter
line from above with the following, and replacing$menu->slug
with your menu’s actual slug name:Source Tutorial
You can set
container
tofalse
and use theitems_wrap
argument to omit theul
, then the function will only output theli
tags, letting you wrap it in whatever you need.