你可以找到这个article I wrote over at WPtuts 有用的
下面的例子是我根据那篇文章改编的。它列出了所有顶级链接,但只探索了“当前”菜单项的祖先。希望评论中的逻辑是明确的:
class WPSE73358_Ancestors_Only_Walker extends Walker_Nav_Menu {
// 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 not the top level nor 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 );
}
}
虽然它扩展了
Walker_Nav_Menu
它的编写使得它可以扩展几乎所有的Walker类(包括基类)。您可能会发现类需要更改,或者-例如,对于post,使用它可能更合适
get_post_ancestors()
相反