Bootstrap badges in nav items

Hi guys,
I’m loving the sh*t out of roots right now but I’m having trouble figuring how to modify the nav walker to do what I want. I need to insert a <span> within the <a> tag that roots outputs by default.

I need to get something like this:

<li class="menu-plaques">
  <a href="/plaques/">Plaques<span class="badge">42<span></a>


You just need a filter and a str_replace:

add_filter('roots_wp_nav_menu_item', 'add_badges_to_menu', 100, 1); 

function add_badges_to_menu($item_html) {
  $num = 42;
  return str_replace('</a>', ' <span class="badge">'. $num .'</span></a>', $item_html);

Gah! I knew it would be that easy. I think I even tried that but did it wrong of course.
I’ve written software for years but only recently started doing wordpress the right way. Roots btw, is TOTALLY the right way.

Oh yah, I also need the span’s to have unique identifiers. I guess I could just target them as .menu-trophies span{} but if I wanted to, how would I reference more info about $item_html

Silly question, this filter goes in functions.php or custom.php?


It will work in either but it’s tidier if you keep it in lib/custom.php.

Each span should have a unique list element as an ancestor, so I would target that: .menu-menu-item > a > .badge

$item_html contains the html for the list item, so you would have to search the string to find more about it, change the filter to additionally pass $item, or add your own filter. All the code is in the nav walker.

1 Like