Adding class in li under WordPress Navigation Menus

In WordPress, you can generate menus by using wp_nav_menu function. It will show the menus you set in admin. Here is the example of menus in html version.

<ul id="menu-header-menu" class="menu">
  <li class="wordpress generated classes">
     <a href="#">Menu Name</a>
  </li>
  <li class="wordpress generated classes">
    <a href="#">Menu has sub menu</a>
   <ul class='sub-menu'>
     <li class="wordpress generated classes">
         <a href="#">sub menu item</a>
     </li>
     <li class="wordpress generated classes">
         <a href="#">another submenu item</a>
     </li>
   </ul>
  </li>
</ul>

For some reason, you want to let your visitors know that the menu has sub menus by showing arrow or drop down icon next to the menu. In this case, you’ll need to add CSS in li element that it has child menu. There is an answer to this on stackoverflow by adding some php codes in functions.php. I found that there is an alternative way to solve this problem by using jQuery. If you’re familiar with jQuery, the following line that I used for my WordPress theme will help you with this problem.

<script type="text/javascript">
        $(document).ready(function(){
            $('.sub-menu').closest('li').addClass('has-submenu');
        });
</script>

You can add the above code before head or at the end of your theme. It will add ‘has-submenu’ in li elements of wordpress menu that has sub menus. I hope this help.


Comments

One response to “Adding class in li under WordPress Navigation Menus”

  1. I love it