2

I'm looking to output the following markup for a menu through wp_nav_menu,

<ul>
        <li><a href="/">Home</a></li>
        <li>
            <a href="/" aria-haspopup="true">Blog</a>
            <ul>
                <li><a href="/">Design</a></li>
                <li><a href="/">HTML</a></li>
                <li><a href="/">CSS</a></li>
                <li><a href="/">JavaScript</a></li>
            </ul>
        </li>
</ul>

The menu items may have submenus - if that's the case the top level link needs to be formatted as the example above. I've tried different solutions looking into the codex but without success. It seems I will need to create a walker for this unless I want to add a bunch of queries (running submenu loops inside a main loop). But since it's such a small change, wouldn't it be possible to add a filter hook onto the menu output instead?

1 Answer 1

8

If I understand correctly, you want links with submenus to have an attribute of aria-haspopup. If this is correct, you should be able to do so using the nav_menu_link_attributes filter (WP 3.6 and above). You can also get around the necessity of having to write a custom Walker to check if an item has children by checking its css classes in the filter.

add_filter( 'nav_menu_link_attributes', 'wpse154485_add_aria_haspopup_atts', 10, 3 );
function wpse154485_add_aria_haspopup_atts( $atts, $item, $args ) {
  if (in_array('menu-item-has-children', $item->classes)) {
    $atts['aria-haspopup'] = 'true';
  }
  return $atts;
}
2
  • Am I right in thinking that only IE 10+ will do anything with the aria-haspopup property? i.e. another solution to handling hover with touch will have to be implemented for other browsers?
    – catdotgif
    Dec 28, 2014 at 6:49
  • I just wanted to add that I've been searching for a while on how to add a button to expand submenu items after the anchor tag (for accordian menu). This code solved my problem if anyone else is interested. Just replace $atts['aria-haspopup'] = 'true'; with $args->after = "";.
    – gavsiu
    Feb 8, 2017 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.