Can you add 'current_menu_item' attribute in a menu loop?

Hey, wasn’t able to find this with a search. I’d like to fetch a WP menu with a LL loop, with the option to add an attribute/style to the result that matches the current page (e.g. highlight the About page link if we’re on the About page). I’d like to add both a class and an aria-current=“page” attribute, if possible.

Is this doable?

Thx,
DB

Hi @gingersoul,

Just a little test, something like that seems to work for adding the current-menu-item class:

<Set current-url><Field url /></Set>
Current URL: <Get current-url />

<ul>
  <Loop type=menu menu="My Menu name" >
    <If variable=current-url is value="{Field url}" >
      <li class="current-menu-item" style="color: red;"><Field title /></li>
    <Else />
      <li><Field title /></li>
    </If>
  </Loop>
</ul>
2 Likes

@avanti this worked perfectly, you’re a genius. What a powerful framework.

2 Likes

@eliot is the genius :grin:

2 Likes

Nice one @avanti! Just to add to the conversation, I thought I’d mention that it might be useful to look into the Url tag since that could allow you to make your template slightly more compact. Something like this:

<ul>
  <Loop type=menu menu="My Menu name" >
    <If field=url is value="{Url current}" >
      <li class="current-menu-item" style="color: red;"><Field title /></li>
    <Else />
      <li><Field title /></li>
    </If>
  </Loop>
</ul>

Another approach that’s maybe a bit more DRY but does involve setting a variable (not necessarily better but just another way to think about this):

<ul>
  <Loop type=menu menu="My Menu name" >
    <If field=url is value="{Url current}">
      <Set menu_attributes>current-menu-item</Set>
    <Else />
      <Set menu_attributes>menu-item</Set>
    </If>
    <li class="some-other-class {Get menu_attributes}"><Field title /></li>
  </Loop>
</ul>
2 Likes

I like the versatility of L&L, despite it lets me confused sometimes. :grin:

1 Like