1

I've this DOM here:

<ul class="sub-menu">
    <li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
        <a href="#">Item</a>
    </li>
</ul>

What I need to do is, to add a custom class (has-ripple) to only the sub-menu > a items:

<ul class="sub-menu">
    <li id="menu-item-1424" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat">
        <a href="#" class="has-ripple">Item</a>
    </li>
</ul>

This is what I've tried:

add_filter( 'nav_menu_link_attributes', 'nav_menu_link_class', 10, 3 );
function nav_menu_link_class( $atts, $item, $args ) {
    $class         = 'has-ripple';
    $atts['class'] = $class;

    return $atts;
}

This works but it also add the class to non-submenu a items outside of the dropdown. So how can I do this right?

2

To be applied to sub-menu items only, your code should be:

add_filter( 'nav_menu_link_attributes', 'nav_menu_link_class', 10, 2 );
function nav_menu_link_class( $atts, $item ) {
    if( !$item->has_children && $item->menu_item_parent > 0 ) {
        $class         = 'has-ripple';
        $atts['class'] = $class;
    }

    return $atts;
}
2

Try this : Documentation

add_filter( 'nav_menu_link_attributes', 'nav_menu_link_class', 10, 4 );

function nav_menu_link_class(  $atts, $item, $args, $depth ) {

      if ( 0 !== $depth ) {
         $class         = 'has-ripple';
         $atts['class'] = $class;
      }
    return $atts;
}

I hope this may help.

  • Where $depth does come from? – Frank P. Walentynowicz Mar 26 at 16:18
  • $depth is 4th parameter passed to callback. Mistake corrected and answer updated. Thanks for helpful reminding! – Qaisar Feroz Mar 26 at 16:36
  • Then add_filter should specify 4 parameters for callback function. – Frank P. Walentynowicz Mar 26 at 16:44
  • You are right. Thanks, once again. – Qaisar Feroz Mar 26 at 16:46
  • What if WordPress version is lower than 4.1.0 ? – Frank P. Walentynowicz Mar 26 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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