wordpress的walker


Updated on: September 16, 2020 in Wordpress by

walker在任何程序里都存在,是一个方法将一个多级的array循环出来。wordpress本身有自带的walker, 很多时候要自定义walker.

start element 函数和end element 函数会循环每个单个的类目,start lvl 和end lvl函数会被读取当循环数据开始时和结束时候, 不会循环,只是在循环开始时候和结束时候读取。

召唤walker的方式是在wp_nav_menu的函数里边,

 <?php wp_nav_menu( array(
              'theme_location'  => 'header',
              'container'  => false,
              'fallback_cb'  => false,
              'walker'  => new Ju_Custom_Nav_Walker(),
  

            ) ); ?>

bootstrap的nav walker:

<?php
        wp_nav_menu( array(
            'theme_location'    => 'primary',
            'depth'             => 2,
            'container'         => 'div',
            'container_class'   => 'collapse navbar-collapse',
            'container_id'      => 'bs-example-navbar-collapse-1',
            'menu_class'        => 'nav navbar-nav',
            'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
            'walker'            => new WP_Bootstrap_Navwalker(),
        ) );
        ?>

简单的walker class:(注意要在functions.php里面include进来或者require进来。

<?php 

class Ju_Custom_Nav_Walker extends Walker_Nav_Menu {
	public function start_lvl(&$output,$depth = 0,$args = []) {
		$output  .= '<ul class="special-class">';
		
	}

	public function start_el(&$output,$item,$depth = 0,$args = [],$id = 0 ) {  //添加 $item 创建 item ,$id 包含这个menu的id ,wordpress 所有menu都有id 
		$output .= '<li class="special-class-item">';
		$output .= $args->before;  //the $args valuble contais the value you should set inside the wp_nav_menu function , 也就是 wp_nav_menu args 里面的 before 和 after ;
		$output .= '<a class="special-list-link" href="' . $item->url . '">';  //item value 包含 menu 的loop; 
		$output .= $args->link_before . $item->title . $args->link_after;

		$output .= '</a>';
		$output .= $args->after;



	}

	public function end_el(&$output,$item,$depth = 0,$args = [],$id = 0) {
		$output .= '</li>';
	}

	public function end_lvl(&$output,$depth = 0,$args = []) {

		$output .= '</ul>';
	}
}  //用walker之后 父级的li 也添加了 class 
//start lv and end lv functions get appied to sub menu item, the start el and end el functions get applied to all menus including  main level ones,  start lvl 函数 应用在子级, start el 函数应用在 全部 
//start element 和 end element  will loop through each individual item, the start level and end level will be called during the beging and ending of the data structure;