Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP / Wordpress - add arrows to parent menus

is it possible to add some kind of class like 'arrow' or a span inside the menus that have submenus (in Wordpress)? it seems that you can do this is using javascript, but I want to know if there's a PHP solution...

in WP 3.0, I saw that active menus have the "parent" or "ancestor" classes on them, but this is only for active menu, and I need it for inactive ones as well

like image 366
Alex Avatar asked Aug 24 '10 15:08

Alex


1 Answers

This functionality really should be in WordPress core!
Anyway, I had a look at the menu template source you sent in a comment on the other answer, and have found a (rather hacky) way to add a class on menu items with children. It basically subclasses the default walker to extend its default behaviour. It's probably best if you put it in your theme's functions.php. Here's the code:

<?php
class Arrow_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[] = 'arrow'; //enter any classname you like here!
        }
        Walker_Nav_Menu::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
    }
}
?>

To call it, you'll need to add the walker argument when you call wp_nav_menu() in your theme, like so:

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

Hope that works for you! I've only tested it superficially, but it seems to work. Let me know if there are any edge cases where adding the class fails.

like image 178
Donald Harvey Avatar answered Sep 18 '22 12:09

Donald Harvey