sage icon indicating copy to clipboard operation
sage copied to clipboard

Vertical menu using Twitter Bootstrap accordion

Open RobertBouten opened this issue 14 years ago • 7 comments

Hi, sorry if I post this in the wrong place. Just started finding my way around here......

Recently I started using Twitter Bootstrap together with Wordpress. Now I would like to make an accordion menu using the collapse feature. Does the roots theme has some way of generating all the classes, data-toggle, id's etc needed for the twitter bootstrap accordion in wp_nav_menu or something??

RobertBouten avatar Aug 22 '12 07:08 RobertBouten

Your original post in the Google group was in the right place. This area is for issues. What you're bringing up is more of a general question which belongs in the Google group.

leoj3n avatar Aug 22 '12 07:08 leoj3n

I don't tend to go on the Google group...

This kind of thing is a nightmare with the walker. It's possible to get the menu items with wp_get_nav_menu_items and I would use that. The following should work although I only tested it with one menu. It makes a few assumptions, e.g. all top levels must have children.

You'll also need to register a menu location in functions.php or change it to use the menu ID.

$menu_name = 'accordion_nav';

    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

    $menu_items = wp_get_nav_menu_items($menu->term_id);

    $menu_list = '<div class="accordion" id="menu-' . $menu_name . '">';

    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title = $menu_item->title;
        $url = $menu_item->url;

        if ($menu_item->menu_item_parent == 0 ) {
        if ($parent > 0) {
        $menu_list .= "</ul>\n</div>\n</div>\n</div>\n\n";
        }
        $menu_list .= "<div class=\"accordion-group\">\n";
        $menu_list .= "<div class=\"accordion-heading\">\n";
                $menu_list .=  "<a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#menu-". $menu_name ."\" href=\"#acc-" . sanitize_title($title) . "\">\n";
                $menu_list .= $title ."\n </a>\n</div>";
                $menu_list .= "<div id=\"acc-" . sanitize_title($title) . "\" class=\"accordion-body collapse\">\n";
        $menu_list .= "<div class=\"accordion-inner\">\n";
        $menu_list .= "<ul class=\"accordion-menu\">\n";
        $parent .= +1;
        } else {
        $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
        }
    }
    $menu_list .= "</ul>\n</div>\n</div>\n</div>\n</div>\n";
    } else {
    $menu_list = '<h4>Menu "' . $menu_name . '" not defined.</h4>';
    }
echo "<!-- START ACCORDION --!>";
 echo $menu_list;
echo "<!-- END ACCORDION --!>";

Foxaii avatar Aug 22 '12 20:08 Foxaii

Thanks a lot, I am going to check it out! Hope I can get it to work.

On Wed, Aug 22, 2012 at 10:45 PM, Foxaii [email protected] wrote:

I don't tend to go on the Google group...

This kind of thing is a nightmare with the walker. It's possible to get the menu items with wp_get_nav_menu_items and I would use that. The following should work although I only tested it with one menu. It makes a few assumptions, e.g. all top levels must have children.

You'll also need to register a menu location in functions.php or change it to use the menu ID.

$menu_name = 'accordion_nav';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

$menu_items = wp_get_nav_menu_items($menu->term_id);

$menu_list = '<div class="accordion" id="menu-' . $menu_name . '">';

foreach ( (array) $menu_items as $key => $menu_item ) {
    $title = $menu_item->title;
    $url = $menu_item->url;

    if ($menu_item->menu_item_parent == 0 ) {
    if ($parent > 0) {
    $menu_list .= "</ul>\n</div>\n</div>\n</div>\n\n";
    }
    $menu_list .= "<div class=\"accordion-group\">\n";
    $menu_list .= "<div class=\"accordion-heading\">\n";
            $menu_list .=  "<a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#menu-". $menu_name ."\" href=\"#acc-" . sanitize_title($title) . "\">\n";
            $menu_list .= $title ."\n </a>\n</div>";
            $menu_list .= "<div id=\"acc-" . sanitize_title($title) . "\" class=\"accordion-body collapse\">\n";
    $menu_list .= "<div class=\"accordion-inner\">\n";
    $menu_list .= "<ul class=\"accordion-menu\">\n";
    $parent .= +1;
    } else {
    $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
    }
}
$menu_list .= "</ul>\n</div>\n</div>\n</div>\n</div>\n";
} else {
$menu_list = '<h4>Menu "' . $menu_name . '" not defined.</h4>';
}echo "<!-- START ACCORDION --!>";

echo $menu_list;echo "<!-- END ACCORDION --!>";

— Reply to this email directly or view it on GitHubhttps://github.com/retlehs/roots/issues/529#issuecomment-7948737.

RobertBouten avatar Aug 22 '12 21:08 RobertBouten

What a relief! I have been fighting for days with the custom walker and javascript. The above code just works perfectly for an accordion menu with one sub level.

Now I would like to extend it to the second sub level. I guess after if ($menu_item->menu_item_parent == 0 ) { .... }

I have to implement elseif ($menu_item->menu_item_parent == 1) { ... }

and put a simular code in between the { } ?

RobertBouten avatar Aug 23 '12 08:08 RobertBouten

That won't work, 'menu_item_parent' refers to the id of the parent so whilst 0 is top-level (no parents), any other number could be any other level.

If you absolutely need something that complex you will have to use the nav walker, where you can call on depth.

I won't be able to help much on this, but the attached should get you started.

Please post the final code when you get it working. It may come in handy.

/**
 * Cleaner walker for wp_nav_menu()
 *
 * Walker_Nav_Menu (WordPress default) example output:
 *   <li id="menu-item-8" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-8"><a href="/">Home</a></li>
 *   <li id="menu-item-9" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-9"><a href="/sample-page/">Sample Page</a></l
 *
 * Roots_Nav_Walker example output:
 *   <li class="menu-home"><a href="/">Home</a></li>
 *   <li class="menu-sample-page"><a href="/sample-page/">Sample Page</a></li>
 */

class Roots_Nav_Walker extends Walker_Nav_Menu {
  function check_current($classes) {
    return preg_match('/(current[-_])|active|dropdown/', $classes);
  }

  function start_lvl(&$output, $depth = 0, $args = array()) {
    $output .= "\n<ul class=\"accordion-menu\">\n";
  }

   function end_lvl(&$output, $depth = 0, $args = array()) {
    $output .= "\n</div>\n</div>\n</div>\n";
  }

  function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
    global $wp_query;
    $indent = ($depth) ? str_repeat("\t", $depth) : '';

    $slug = sanitize_title($item->title);
    $id = 'menu-' . $slug;

    $class_names = $value = '';
    $li_attributes = '';
    $classes = empty($item->classes) ? array() : (array) $item->classes;

    $classes = array_filter($classes, array(&$this, 'check_current'));

    $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
    $class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';

    if ($args->has_children && $depth == 0){

        $output .= "<div class=\"accordion-group\">\n";
        $output .= "<div class=\"accordion-heading\">\n";
                $output .=  "<a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#acc-menu-$args->theme_location\" href=\"#acc-" . sanitize_title($item->title) . "\">\n";
                $output .= $item->title ."\n </a>\n</div>";
                $output .= "<div id=\"acc-" . sanitize_title($item->title) . "\" class=\"accordion-body collapse\">\n";
        $output .= "<div class=\"accordion-inner accordion-'.sanitize_title($item->title) .'\">\n";

    } else {
    $output .= $indent . '<li' . $class_names . '>';

    $attributes  = ! empty($item->attr_title) ? ' title="'  . esc_attr($item->attr_title) .'"' : '';
    $attributes .= ! empty($item->target)     ? ' target="' . esc_attr($item->target    ) .'"' : '';
    $attributes .= ! empty($item->xfn)        ? ' rel="'    . esc_attr($item->xfn       ) .'"' : '';
    $attributes .= ! empty($item->url)        ? ' href="'   . esc_attr($item->url       ) .'"' : '';

    $item_output  = $args->before;
    $item_output .= '<a'. $attributes .'>';
    $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
    $item_output .= ($args->has_children && $depth == 0) ? ' <b class="caret"></b>' : '';
    $item_output .= '</a>';
    $item_output .= $args->after;
    }
    $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
  }

  function display_element($element, &$children_elements, $max_depth, $depth = 2, $args, &$output) {
    if (!$element) { return; }

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

    if (is_array($args[0])) {
      $args[0]['has_children'] = !empty($children_elements[$element->$id_field]);
    } elseif (is_object($args[0])) {
      $args[0]->has_children = !empty($children_elements[$element->$id_field]);
    }

    $cb_args = array_merge(array(&$output, $element, $depth), $args);
    call_user_func_array(array(&$this, 'start_el'), $cb_args);

    $id = $element->$id_field;

    if (($max_depth == 0 || $max_depth > $depth+1) && isset($children_elements[$id])) {
      foreach ($children_elements[$id] as $child) {
        if (!isset($newlevel)) {
          $newlevel = true;
          $cb_args = array_merge(array(&$output, $depth), $args);
          call_user_func_array(array(&$this, 'start_lvl'), $cb_args);
        }
        $this->display_element($child, $children_elements, $max_depth, $depth + 1, $args, $output);
      }
      unset($children_elements[$id]);
    }

    if (isset($newlevel) && $newlevel) {
      $cb_args = array_merge(array(&$output, $depth), $args);
      call_user_func_array(array(&$this, 'end_lvl'), $cb_args);
    }

    $cb_args = array_merge(array(&$output, $element, $depth), $args);
    call_user_func_array(array(&$this, 'end_el'), $cb_args);
  }
}

/**
 * Cleanup wp_nav_menu_args
 *
 * Remove the container
 * Use Roots_Nav_Walker() by default
 */
function roots_nav_menu_args($args = '') {
  $roots_nav_menu_args['container']  = false;
  $roots_nav_menu_args['items_wrap'] = '<div id="acc-menu-'. $args[theme_location] .'" class="%2$s accordion">%3$s</div></div></div></div>';
  if (current_theme_supports('bootstrap-top-navbar')) {
    $roots_nav_menu_args['depth'] = 2;
  }

  if (!$args['walker']) {
    $roots_nav_menu_args['walker'] = new Roots_Nav_Walker();
  }

  return array_merge($args, $roots_nav_menu_args);
}

add_filter('wp_nav_menu_args', 'roots_nav_menu_args');

Foxaii avatar Aug 23 '12 12:08 Foxaii

Oke, I hope I find the time in the next few days to start the battle with this bit of code...

RobertBouten avatar Aug 23 '12 21:08 RobertBouten

Thanks Foxaii. Much appreciated!

ghost avatar May 27 '15 21:05 ghost