我可以扩展Walker\\u Nav\\u Menu类,但在查看它之后,似乎无法知道子菜单何时将包含其他子菜单,因为没有关于其子菜单的可用数据
你可能想再看看,伙计。
这个Walker::display_element(...) 方法将“要继续遍历的元素列表”(了解子元素列表)作为第二个参数:array$children\\u elements
如果你做了
var_dump($children_elements);
您将看到菜单中的每个条目。为了知道条目是否包含子元素,可以检查$children\\u elements[$id]是否为空,其中$id是相关元素的id:
$this->has_children = ! empty( $children_elements[ $id ] );
因此,您可以检查菜单中的每个条目是否有子项,如果有,请检查是否有任何子项有自己的子项:
<?php
/**
* menu_walker
*
* @since 1.0.0
* @package My Theme Wordpress
*/
if ( ! class_exists( \'MyThemeWP_Top_Menu_Walker\' ) ) {
class MyThemeWP_Top_Menu_Walker extends Walker_Nav_Menu {
/**
* Find menu elements with children containing children and give them the super-parent-class class
* Then call the default display_element method
*/
public function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
if ( ! $element ) {
return;
}
$id_field = $this->db_fields[\'id\'];
$id = $element->$id_field;
//var_dump($children_elements[ $id ]); // List the children elements of the element with $id
$this->has_children = ! empty( $children_elements[ $id ] );
if ( isset( $args[0] ) && is_array( $args[0] ) ) {
$args[0][\'has_children\'] = $this->has_children; // Back-compat.
}
// If this element have children
if ( ! empty( $children_elements[$id] ) //&& ( $depth == 0 ) // Remove this comment to apply the super-parent-class only to root elements
//|| $element->category_post != \'\' && $element->object == \'category\'
) {
// var_dump($children_elements[$id]);
// Loop through it\'s children
foreach ($children_elements[$id] as &$child_element) {
//var_dump($child_element->ID);
//var_dump(! empty( $children_elements[$child_element->ID] ));
// If this child has children of it\'s own, add super-parent-class to it\'s parent
if ( ! empty( $children_elements[$child_element->ID] ) ){
$element->classes[] = \'super-parent-class\';
}
}
}
// Call default method from virtual parent class
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
} // class MyThemeWP_Top_Menu_Walker END
}
?>