WordPress Snippets at WPcustoms

Build a WordPress and Bootstrap ready Menu

An outstanding work from rootstheme. These functions drop all those post and menu classes, set the new walker as default WordPress navigation walker and also converts the code to bootstrap ready navbars. One of my favorite snippets and used on every site I build.


/**
 * Snippet Name: Build a WordPress and Bootstrap ready Menu
 * Snippet URL: https://wpcustoms.net/snippets/build-a-wordpress-and-bootstrap-ready-menu/
 */
  /**
 * Cleaner walker for wp_nav_menu()
 *
 * Walker_Nav_Menu (WordPress default) example output:
 *   
  • Home
  • *
  • Sample PageHome
  • * */ 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
      \n"; } function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { $item_html = ''; parent::start_el($item_html, $item, $depth, $args); if ($item->is_dropdown && ($depth === 0)) { $item_html = str_replace('', ' ', $item_html); } elseif (stristr($item_html, 'li class="divider')) { $item_html = preg_replace('/]*>.*?<\/a>/iU', '', $item_html); } elseif (stristr($item_html, 'li class="dropdown-header')) { $item_html = preg_replace('/]*>(.*)<\/a>/iU', '$1', $item_html); } $item_html = apply_filters('roots_wp_nav_menu_item', $item_html); $output .= $item_html; } function display_element($element, &$children_elements, $max_depth, $depth = 0, $args, &$output) { $element->is_dropdown = ((!empty($children_elements[$element->ID]) && (($depth + 1) < $max_depth || ($max_depth === 0)))); if ($element->is_dropdown) { $element->classes[] = 'dropdown'; } parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output); } } /** * Remove the id="" on nav menu items * Return 'menu-slug' for nav menu classes */ function roots_nav_menu_css_class($classes, $item) { $slug = sanitize_title($item->title); $classes = preg_replace('/(current(-menu-|[-_]page[-_])(item|parent|ancestor))/', 'active', $classes); $classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes); $classes[] = 'menu-' . $slug; $classes = array_unique($classes); return array_filter($classes, 'is_element_empty'); } add_filter('nav_menu_css_class', 'roots_nav_menu_css_class', 10, 2); add_filter('nav_menu_item_id', '__return_null'); /** * Clean up 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; if (!$args['items_wrap']) { $roots_nav_menu_args['items_wrap'] = '
        %3$s
      '; } if (current_theme_supports('bootstrap-top-navbar') && !$args['depth']) { $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');