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

<ul>
        <li><a href="https://wordpress.stackexchange.com/">Home</a></li>
        <li>
            <a href="https://wordpress.stackexchange.com/" aria-haspopup="true">Blog</a>
            <ul>
                <li><a href="https://wordpress.stackexchange.com/">Design</a></li>
                <li><a href="https://wordpress.stackexchange.com/">HTML</a></li>
                <li><a href="https://wordpress.stackexchange.com/">CSS</a></li>
                <li><a href="https://wordpress.stackexchange.com/">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

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *