I want to add a span to top level links of a wordpress menu called "main".
The desired html output (wordpress classes removed for a clear visual) would look like so:
<ul>
<li><a href="#"><span>Link</span></a></li>
<li><a href="#"><span>Link</span></a>
<ul>
<li><a href="#">Sub Link (no span)</a></li>
<li><a href="#">Sub Link (no span)</a></li>
<li><a href="#">Sub Link (no span)</a></li>
</ul>
</li>
<li><a href="#"><span>Link</span></a></li>
<li><a href="#"><span>Link</span></a></li>
</ul>
I found this wordpress filter some time ago when Googling (most likely stack overflow, can't remember where) that adds the span nicely, but it adds it to every menu in my theme.
add_filter( 'wp_nav_menu_objects', function( $items ) {
foreach ( $items as $item ) {
if (!$item->menu_item_parent) {
$item->title = '<span>' . $item->title . '</span>';
}
}
return $items;
});
Q1. Is there a way to add this filter just to the menu called main?
Q2. Is that the best filter / way to achieve this?
Thanks for any help.