Reputation: 239
I am trying to add a div after any submenu items in a WordPress menu. I am working on the following code in the functions.php file:
add_filter( 'nav_menu_link_attributes', 'SubMenuCheck', 10, 3 );
function SubMenuCheck( $atts, $item, $args ) {
if (in_array('menu-item-has-children', $item->classes)) {
$args->after = '<div class="click">+</div>';
}
return $atts;
}
The code above adds the new div <div class="click">+</div>
but keeps applying it to all parent and child items after the first 'menu-item-has-children' class:
Does anyone know why this is repeating?... I only want the div to display for items with the menu-item-has-children
class.
Thanks
Upvotes: 0
Views: 2882
Reputation: 34652
I don't use the nav_menu_link_attributes
filter, to add a button (which is semantically correct) to be the hot spot for toggling the children, I use the following:
function prefix_add_button_after_menu_item_children( $item_output, $item, $depth, $args ) {
if ( $args->theme_location == 'primary' ) {
if ( in_array( 'menu-item-has-children', $item->classes ) || in_array( 'page_item_has_children', $item->classes ) ) {
$item_output = str_replace( $args->link_after . '</a>', $args->link_after . '</a><button class="sub-menu-toggle" aria-expanded="false" aria-pressed="false"><span class="screen-reader-text">' . _x( 'open dropdown menu', 'verb: open the menu', 'text-domain' ) . '</span></button>', $item_output );
}
}
return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'prefix_add_button_after_menu_item_children', 10, 4 );
Upvotes: 5