WordPress本机Walker
类不会将所需的参数传递给start_lvl()
方法为此,您需要添加一个自定义display_element()
方法创建自定义walker。您可以使用大部分原始内容,与下面的注释部分类似:
public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( ! $element ) {
return;
}
$id_field = $this->db_fields[\'id\'];
$id = $element->$id_field;
//display this element
$this->has_children = ! empty( $children_elements[ $id ] );
if ( isset( $args[0] ) && is_array( $args[0] ) ) {
$args[0][\'has_children\'] = $this->has_children; // Backwards compatibility.
}
$cb_args = array_merge( array( &$output, $element, $depth ), $args );
call_user_func_array( array( $this, \'start_el\' ), $cb_args );
// descend only when the depth is right and there are childrens for this element
if ( ( $max_depth == 0 || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {
foreach ( $children_elements[ $id ] as $child ) {
if ( ! isset( $newlevel ) ) {
$newlevel = true;
//start the child delimiter
$cb_args = array_merge( array( &$output, $depth ), $args );
/** Additional check for custom addition of id to sub-level */
if ( $element->post_name = \'Megatron\' ) {
$cb_args[\'sub_menu_id\'] = \'megatron\';
}
/** End custom check */
call_user_func_array( array( $this, \'start_lvl\' ), $cb_args );
}
$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
}
unset( $children_elements[ $id ] );
}
if ( isset( $newlevel ) && $newlevel ) {
//end the child delimiter
$cb_args = array_merge( array( &$output, $depth ), $args );
call_user_func_array( array( $this, \'end_lvl\' ), $cb_args );
}
//end this element
$cb_args = array_merge( array( &$output, $element, $depth ), $args );
call_user_func_array( array( $this, \'end_el\' ), $cb_args );
}
此处添加的代码检查主元素名称,然后将id信息附加到将发送到的参数
start_lvl()
.
现在,您可以在start_lvl()
方法,例如:
public function start_lvl( &$output, $depth = 0, $args = array(), $sub_menu_div = null ) {
$indent = str_repeat("\\t", $depth);
if ( $sub_menu_div ) {
$output .= "\\n$indent<div id=\\"$sub_menu_div\\"><ul class=\\"sub-menu\\">\\n";
} else {
$output .= "\\n$indent<ul class=\\"sub-menu\\">\\n";
}
}
希望这有帮助。祝你好运