Add custom class to WordPress menu using wp_nav_menu function

No comments
WordPress has a very good functionality of creating menu by dragging and dropping to required places and creating child or sub child menu in same way, that helps a layman to create menu very easily within a minute or two. However; if you are a developer and you want to go deeper in the functionality such as if you want to add a class to the parent UL or you want to add an ID to the parent UL tag then you will need to edit the source code.

Generally, we call wp_nav_menu() as following:
<?php wp_nav_menu( array('theme_location' => 'primary','menu_id' => 'mainHdrMenuId','menu_class' => 'hdrnavLst pull-right', )); ?>

In Above example, I have used 'primary' navigation in theme_location parameter that i already have created a menu in WordPress admin and also assigned 'mainHdrMenuId' as menu id and added two class in the menu_class parameter However; the classes and ids will be applied to the parent div section and not in UL tag.

If you want to add the class in UL section then you must have to define ul as a container in wp_nav_menu() function and then the defined id and classes will applied only to ul tag not to the parent div that WordPress by default add. See the example below:
<?php wp_nav_menu( array('theme_location' => 'primary','container'=> 'ul', 'menu_id' => 'mainHdrMenuId','menu_class' => 'hdrnavLst pull-right', )); ?>

I Hope this trick will help you. Please share your feedback in the comment box below.

No comments :

Post a Comment