With some preg_replace, I can replace some classes in the wp_nav_menu, so one of my menu (which has submenu) now looks like this.

<li class="nav-item nav-item-has-children dropdown menu-publication show">
    <a class="nav-link" href="#">Publication</a>
    <ul class="dropdown-menu">
        <li class="nav-item menu-book">
            <a class="nav-link" href="#">Book</a>

However, I also need to replace the <a> element (the .nav-link) so that the <a> would look like this:

<a class="nav-link" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" href="#">Publication</a>

Problem is, I only want to replace the anchor which has submenu. I don't want to meddle with <a> that got no submenu. I can't figure it out how to do this. Is there any idea?

Preferably without remaking the whole menu walker...

I'm thinking of doing this:

function change_submenu_link($submenulink) {    
    return preg_replace('/a class="nav-link"/','class="nav-link" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"',$submenulink);


Problem is I don't know to make sure that it only replaces the <a> that got submenu. If there's a has_submenu() function maybe it could be handy.

  • Hi. Please share your current code, so we can add the necessary code to make it work the way you want.
    – Johansson
    Jun 19, 2017 at 17:45
  • @JackJohansson Added, I hope my question is clear enough. Not a native speaker here, having difficulties to explain what I meant....
    – deathlock
    Jun 19, 2017 at 17:53
  • 1
    wordpress.stackexchange.com/questions/154485/… should provide insight on how to tell if a menu item has children
    – mrben522
    Jun 19, 2017 at 17:59
  • 2
    Just to note: the nav_menu_link_attributes filter, which the answer @mrben522 linked to uses, should also be used to change the classes. Editing the entire output using Regex should be avoided, when possible, since it's relatively slow. Jun 19, 2017 at 18:08

1 Answer 1


You should be able to use nav_menu_link_attributes to add attributes to links output by wp_nav_menu that have child/submenu links.

wp_nav_menu conditionally assigns classes to links it outputs. You need to target links with the class .menu-item-has-children

You can add the attributes you want with the following filter/function:

add_filter( 'nav_menu_link_attributes', 'wpse270596_add_navlink_atts', 10, 3 );
function wpse270596_add_navlink_atts( $atts, $item, $args ) {
  if (in_array('menu-item-has-children', $item->classes)) {
    $atts['data-toggle'] = 'dropdown';
    $atts['aria-haspopup'] = 'true';
    $atts['aria-expanded'] = 'true';
return $atts;

Your Answer

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

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