A-A+
让WordPress的 wp_nav_menu 函数支持Bootstrap 3
WordPress的菜单函数wp_nav_menu()输出了固定的html结构,我们可以基于这些结构写CSS样式。如果你主题的CSS是基于BootStrap开发的,直接使用BootStrap的导航样式无疑是一种省时省力的方法,我们只需要修改一下WordPress wp_nav_menu() 函数输出的HTML结构,让它和bootstrap的一样就可以了。
第一步: 添加自定义Walker_Nav_Menu 类到主题的 functions.php
class BS3_Walker_Nav_Menu extends Walker_Nav_Menu { function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) { $id_field = $this->db_fields['id']; if ( isset( $args[0] ) && is_object( $args[0] ) ) { $args[0]->has_children = ! empty( $children_elements[$element->$id_field] ); } return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if ( is_object($args) && !empty($args->has_children) ) { $link_after = $args->link_after; $args->link_after = ' '; } parent::start_el($output, $item, $depth, $args, $id); if ( is_object($args) && !empty($args->has_children) ) $args->link_after = $link_after; } function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = ''; $output .= "$indent<ul class=\"dropdown-menu list-unstyled\">"; } }
第二步, 添加filter功能过滤修改上一步未能修改的HTML
add_filter('nav_menu_link_attributes', 'nav_link_att', 10, 3); function nav_link_att($atts, $item, $args) { if ( $args->has_children ) { $atts['data-toggle'] = 'dropdown'; $atts['class'] = 'dropdown-toggle'; } return $atts; }
第三步, 添加HTML到 header.php 中
<nav id="nav" role="navigation"> <div> <div> <div> <!-- Brand and toggle get grouped for better mobile display --> <div> <button type="button" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span>Toggle navigation</span> <span></span> <span></span> <span></span> </button> <a href="#"></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div> <?php wp_nav_menu(array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'items_wrap' => '<ul id="%1$s">%3$s</ul>', 'walker' => new BS3_Walker_Nav_Menu, 'menu' => 'Your Menu' )); ?> </div><!-- /.navbar-collapse --> </div> </div> </div> </nav>