phpwordpressnavigationnavwp-nav-walker

WordPress how to add <span> after main navigation dropdown


I like to add an empty 'span' in the main navigation li element which has a specific class.

Here is the desired look:

<ul>
<li class="menu-item"><a href="#" class="nav-link"></a></li>
<li class="menu-item"><a href="#" class="nav-link"></a></li>
<li class="menu-item has-childern"><a href="#" class="nav-link"></a><span></span></li>
</ul>

I have a code that adds the span after every nav link:

add_filter('nav_menu_item_args', function ($args, $item, $depth) {
if ( $args -> theme_location == 'primary') {
    $args -> link_after  = '<span></span>';
}
    return $args;
}, 10, 3);

How can I achieve to add the 'span' only in the 'li' element which has the 'has-children' class? Thank you for the help!


Solution

  • You could use nav_menu_link_attributes filter hook to get access to the nav attributes.

    From Documentation
    nav_menu_link_attributes

    • 'after'
      (string) Text after the link markup.
    • 'link_after'
      (string) Text after the link text.

    So you could set it up in multiple ways, for example you could do something like this:

    add_filter('nav_menu_link_attributes', 'your_theme_custom_html_element', 10, 3);
    
    function your_theme_custom_html_element($atts, $item, $args)
    {
    
      if ($args->theme_location == 'primary' && (strpos($atts['class'], 'has-childern') !== false)) {
    
        $args->after  = '<span></span>';
    
      }
    
      return $atts;
    }
    

    Just tested on my own website and it works seamlessly fine!