Display only page specific sub menu items using Custom Walker

Here is a much simpler implementation:

class UL_Submenu_Walker extends Walker_Nav_Menu {
    private $hidden = false;

    function start_lvl(&$output, $depth) {
        if($depth == 0) {
            $style = $this->hidden ? "" : "display:none;";
        }
        $output .= "<ul class=\"submenu-".$depth."\" style="".$style."">";
    }

    function start_el(&$output, $item, $depth, $args) {
        $class_names = $value="";

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;  

        if ($depth == 0 &&
                (in_array("current-menu-item", $classes) ||
                 in_array('current-menu-parent', $classes) ||
                 in_array('current-menu-ancestor', $classes)) ) {
            $this->hidden = true;
        } else {
            $this->hidden = false;
        }
        parent::start_el($output, $item, $depth, $args);
    }
}

I’m sure this will need some optimization, but it works.

Leave a Comment