Search code examples
phpwordpressmenuchildren

PHP/Wordpress - Attach a class to a child <ul>


I'm trying to attach a class to a <ul> tag within a <li> tag (i.e. a child <ul>)

It is for a Wordpress menu, thus I need to create a function for a Walker_Nav_Menu extension and call it within the code.

I'm already able to attach a class to any <li> with children, but I also need to a class to that child.

My current code is below and works (aside from the pseudo-code):

class children_classes extends Walker_Nav_Menu {
    function display_element($element, &$children_elements, $max_depth, $depth, $args, &$output) {

        $id_field = $this->db_fields['id'];

    //If the current element has children, add class 'dropdown'
    if(isset($children_elements[$element->$id_field])) { 
        $classes = empty($element->classes) ? array() : (array) $element->classes;
        $classes[] = 'dropdown';
        $element->classes = $classes;

        // Pseudo-code
        Get child ul
          Attach class "dropdown-menu"
        // End psuedo-code
    }

    // We don't want to do anything at the 'top level'.
    if(0 == $depth)
        return parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);

    return parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
    }
}

Solution

  • Add this to your Walker Class:

    function start_lvl(&$output, $depth)
    {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class='sub-menu custom-class'>\n";
    }
    

    This will override the default start_lvl function to add classes or anything else you might need, however you need.