walker类是一个抽象类,旨在帮助遍历和显示具有层次(或树状)结构的元素。它实际上并不“做”(在生成HTML的意义上)任何事情。
在模板文件中,我们将使用wp\\u nav\\u menu()函数两次,指向相同的主题位置(我将其称为“primary”)。如果您还没有注册主题位置,那么应该阅读本文。无论使用哪个主题位置,都应该将菜单保存到该位置。我们将显示此菜单两次。首先,无论您想在哪里显示“顶级”菜单:
wp_nav_menu( array(\'theme_location\'=>\'primary\',\'depth\' => 1) );
然后,使用自定义walker,仅显示(相关)子页面。
wp_nav_menu( array(\'theme_location\'=>\'primary\',\'walker\' => new SH_Child_Only_Walker(),\'depth\' => 0) );
我遵循以下示例:
class SH_Child_Only_Walker extends Walker_Nav_Menu {
// Don\'t start the top level
function start_lvl(&$output, $depth=0, $args=array()) {
if( 0 == $depth )
return;
parent::start_lvl(&$output, $depth,$args);
}
// Don\'t end the top level
function end_lvl(&$output, $depth=0, $args=array()) {
if( 0 == $depth )
return;
parent::end_lvl(&$output, $depth,$args);
}
// Don\'t print top-level elements
function start_el(&$output, $item, $depth=0, $args=array()) {
if( 0 == $depth )
return;
parent::start_el(&$output, $item, $depth, $args);
}
function end_el(&$output, $item, $depth=0, $args=array()) {
if( 0 == $depth )
return;
parent::end_el(&$output, $item, $depth, $args);
}
// Only follow down one branch
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
// Check if element as a \'current element\' class
$current_element_markers = array( \'current-menu-item\', \'current-menu-parent\', \'current-menu-ancestor\' );
$current_class = array_intersect( $current_element_markers, $element->classes );
// If element has a \'current\' class, it is an ancestor of the current element
$ancestor_of_current = !empty($current_class);
// If this is a top-level link and not the current, or ancestor of the current menu item - stop here.
if ( 0 == $depth && !$ancestor_of_current)
return
parent::display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output );
}
}