1

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!

Ruvee
  • 8,611
  • 4
  • 18
  • 44
Nadam
  • 39
  • 1
  • 6
  • 1
    I found the answer here: https://stackoverflow.com/questions/44396980/adding-div-after-wordpress-submenu-items - Ruvee thans for all your effort! – Nadam May 23 '21 at 12:08
  • Well, thanks for providing me with `feedbacks` and also `sharing` the solution. – Ruvee May 24 '21 at 15:11

1 Answers1

1

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!

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • Thank you for your answer Ruvee! Your code almost work as I needed: my problem is, that it adds the span to all the nav items after the the one that contains that specific class. Check this out: https://prnt.sc/139rnoq - only the Dropdown menu has the 'dropdown-toggle' class, but the spans appear at the others too. I can't figure out, why is this happening, 'cause your code seems good to me. – Nadam May 22 '21 at 16:49
  • Well, my code adds the `` anywhere that there is a class called "has-childern". – Ruvee May 22 '21 at 17:35
  • I didn't change your code and it'sseems good, but for me it adds the spans to menu items that doesn't have the 'has-children' class too. I'm trying to figure out how it goes. – Nadam May 23 '21 at 11:50
  • Yea i know it happens sometimes. Like i said, i simulated the same `html` markup, you provided in your question, on my own website and it works exactly what you needed it to. So to further debug it and customize it, i need to see your exact `html` markup. If you want to, you could provide me with a screenshot of your `html` matkup and/or edit your question to include the main `html`. – Ruvee May 23 '21 at 14:34