将以下内容放入functions.php
class SH_Last_Walker extends Walker_Nav_Menu{
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
$id_field = $this->db_fields[\'id\'];
//If the current element has children, add class \'sub-menu\'
if( isset($children_elements[$element->$id_field]) ) {
$classes = empty( $element->classes ) ? array() : (array) $element->classes;
$classes[] = \'has-sub-menu\';
$element->classes =$classes;
}
// We don\'t want to do anything at the \'top level\'.
if( 0 == $depth )
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
//Get the siblings of the current element
$parent_id_field = $this->db_fields[\'parent\'];
$parent_id = $element->$parent_id_field;
$siblings = $children_elements[ $parent_id ] ;
//No Siblings??
if( ! is_array($siblings) )
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
//Get the \'last\' of the siblings.
$last_child = array_pop($siblings);
$id_field = $this->db_fields[\'id\'];
//If current element is the last of the siblings, add class \'last\'
if( $element->$id_field == $last_child->$id_field ){
$classes = empty( $element->classes ) ? array() : (array) $element->classes;
$classes[] = \'last\';
$element->classes =$classes;
}
return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
}
用法
wp_nav_menu
如果要添加“last”类,请在上面指定walker:
wp_nav_menu( array(\'theme_location\'=>\'primary\',\'walker\' => new SH_Last_Walker(),\'depth\' => 0) );
theme_location
和
depth
你可以随心所欲,重要的是
walker
属性
旁白可以改进此代码-通过取消设置$children_elements[$parent_id]
调用时使用数组,并检查何时使用到最后一个元素(即仅包含一个元素)。我想wp_list_filter
在这里很合适。这可能不会提高效率,但可能更整洁。
此外,您还可以对父字段和id字段进行硬编码-我这样做不是为了便于移植。下面的类可以扩展Walker类提供的任何扩展(页面列表、类别列表等)。