输出Bootstrap风格化的wordpress菜单

Author: 陌小雨Date: 2020-09-01View: 120

WordPress菜单是用wp_nav_menu函数来实现的,可以通过一点个性化修改使其变成bootstrap的风格

首先选武器,添加自定义的类BS3_Walker_Nav_Menu extends Walker_Nav_Menu 代码如下:

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\">";
        }

}

然后化化妆,对nav_menu_link_attributes添加钩子,

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;
}

最后凹造型

<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>