WordPress Add Class To Parent Menu Item Or Add Arrows To Parent Menu Item

Posted by Ankur Gandhi in Wordpress



Wordpress Development

Hello Friends, WordPress provides many things which can be done by anyone even who don’t have technical knowledge by simple functions and plugins like using widgets, custom menus,, custom post types etc.. But it is obvious that even after giving too much flexibility by WordPress many clients or user found some things which can’t be done easily by plugins or WordPress features. I found same thing with WordPress menu, I wanted to show arrow image or “>” in parent menu So I need to add class ‘parent-item’ to parent menu item if it is having sub menu(s) and via that class I can add background image or can do any other thing.

So I thought to achieve it by extending ‘Walker_Nav_Menu’ class, in this class we will check if menu have child menus or not and if it is having child menus then add class ‘parent-item’ to parent menu item. So below is code which you need to add to your theme’s functions.php file.

<?php
class Parent_Walker_Nav_Menu extends Walker_Nav_Menu {
    function display_element($element, &$children_elements, $max_depth, $depth=0, $args, &$output) {
        $id_field = $this->db_fields['id'];
        if (!empty($children_elements[$element->$id_field])) {
            $element->classes[] = 'parent-item'; //your classname, you can change it here!
        }
        Walker_Nav_Menu::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
    }
}
?>

So above code add to functions.php file. In above code we are just extending WordPress core class ‘Walker_Nav_Menu’ and then in display_element function we are just checking that if parent item having submenu or not and if it is having sub menu then adding ‘parent-item’ class into array and then pass that array to WordPress core class ‘Walker_Nav_Menu’ display_element function.

Now after adding this code to functions.php file you need to add Walker argument with new Walker class made by us above in wp_nav_menu() like below.

<?php
wp_nav_menu(array('walker' => new Parent_Walker_Nav_Menu, [other arguments here...]))
?>

So after adding walker argument to wp_nav_menu() You will see ‘parent-item’ class will be added to each parent menu item and by that class you can add arrow or add any sign for parent item.

I am WordPress Freelancer India and I am always trying to explain issues on my site and try to give perfect solution for it, So it can help to my readers. Let me know if you got any problem with above code, I will try to help you.

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.