Ferdia O'Brien
Ferdia O'Brien

Reputation: 869

Add class to the link before a sub-menu, not the list item before it

I am looking to do almost exactly what this function does in Wordpress:

add_filter('wp_nav_menu_objects', function ($items) {
    $hasSub = function ($menu_item_id, &$items) {
        foreach ($items as $item) {
            if ($item->menu_item_parent && $item->menu_item_parent==$menu_item_id) {
                return true;
             }
         }
         return false;
     };

     foreach ($items as &$item) {
         if ($hasSub($item->ID, &$items)) {
             $item->classes[] = 'menu-parent-item'; // all elements of field "classes" of a menu item get join together and render to class attribute of <li> element in HTML
         }
     }
     return $items;    
 });

This handy function attaches a class "menu-parent-item" to the li that contains a sub-menu. What I would like to do is add that same class (or any other usable class of course) to the link beforehand instead. In other words I would end up with this:

<li>
    <a href="index.php" class="menu-parent-item">Homepage</a>
    <ul class="sub-menu">
        <li>

And so forth. Any ideas?

Upvotes: 0

Views: 329

Answers (1)

Xhynk
Xhynk

Reputation: 13890

You could always use jQuery

$('ul.sub-menu').parent().addClass('menu-parent-item');

EDIT: well, with your edit, you could just use the prev() method?

$('ul.sub-menu').prev().addClass('menu-parent-item');

Upvotes: 1

Related Questions