Hello guys, Today I come with one very small and useful solution of WordPress. WordPress is very popular CMS platform in PHP and provides extremely useful feature is hooks which are very important when you want to customize your WordPress developed functionalities.
Menu navigation is an important part of any site development. Sometimes you want to add a custom class in the output menu in the WordPress as per your project requirement. So, you can change the menu class easily by applying parameter in wp_nav_menu function but it changes the all menu class.What if you have a hierarchical menu? and you only want to apply the class to parent menu then? At that time you need to write the custom code which will apply the class to the parent menu only.
Here I am going to share about to change the menu with the class name of children or submenu. And you know WordPress provides the hook for that also so you can do it very easy manner.
So, Let us check out code and get into the depth
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Change Parent Menu with Children Class Name function add_parent_menu_class( $items ) { $parents = array(); foreach ( $items as $item ) { if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) { $parents[] = $item->menu_item_parent; } } foreach ( $items as $item ) { if ( in_array( $item->ID, $parents ) ) { } } return $items; } |
The filter name is wp_nav_menu_objects using that you can find and customize the current menu items.This filter first view at the filter value before calling wp_nav_menu and find information on current menu item such as menu ID, title, class or URL, etc. recorded in a global variable.Once the call the menu using the wp_nav_menu function, it will use settings set using wp_nav_menu_objects filter to display the information.
That’s it.Isn’t it easy and understandable? You just need place filter and function into your theme’s functions.php file and you are ready to go.
This function adds the class to the parent menu if menu contains a submenu but you can modify as you want.This function will check if menu contains a submenu and it is parent menu then it will add the class to this menu.
You can add this function and modify as you want. Like you can add class to the submenu or activate submenu.
Hope this function will be useful to you.Share your comments or suggestions to improve this article or may be another super easy method to achieve this.