输出Bootstrap风格化的wordpress菜单

Author: 陌小雨Date: 2024-12-20View: 194

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

然后化化妆,对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;
}

最后凹造型