0

I have a nested dropdown. On elements that have children, I would like to add a chevron beside the link text. The current HTML looks like this:

<ul class="primary-menu">
    <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has- 
    children menu-item-59">
        <a href="#">Europe</a>
        <ul class="sub-menu"></ul>
    </li>
</ul>

I would like to use an add_filter hook to turn this markup into this:

<ul class="primary-menu">
    <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has- 
    children menu-item-59">
        <div>
          <a href="#">Europe</a>
          <img src="chevron.svg">
        </div>
        <ul class="sub-menu"></ul>
    </li>
</ul>

I was hoping to find a filter that would return me an array of menu items. If the menu item has the class of 'menu-item-has-children' I would like to change the HTML within the item.

1

There is indeed a filter, walker_nav_menu_start_el will be able to handle it for you!

Take this code for example:

function wpse356896_filter_primary_nav_menu_dropdown( $item_output, $item, $depth, $args ) {

    // Only for our primary menu location.
    if ( empty( $args->theme_location ) || 'primary-menu' !== $args->theme_location ) {
        return $item_output;
    }

    // Add the dropdown for items that have children.
    if ( ! empty( $item->classes ) && in_array( 'menu-item-has-children', $item->classes ) ) {
        return $item_output . '<span class="dropdown"><img src="chevron.svg"></span>';
    }

    return $item_output;
}

add_filter( 'walker_nav_menu_start_el', 'wpse356896_filter_primary_nav_menu_dropdown', 10, 4 );

| improve this answer | |

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.