故障排除启用WP_DEBUG 常量inwp-config.php 暴露了以下错误:
-函数签名
如果启用了严格标准,您将看到一个错误,详细说明不兼容的方法签名。虽然不是绝对必要,但我喜欢尽可能多地消除错误。要更正此问题,新的
Walker_Nav_Menu 类别的
start_el() 和
start_lvl() 方法的声明需要匹配
those of Walker_Nav_Menu class itself 这样,新类就可以作为
Walker_Nav_Menu 类,而不会引发各种与参数/参数相关的错误。
这是:
class Wpse_145991_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth ) {
//...
}
public function start_el( &$output, $item, $depth, $args ) {
//...
}
}
应该变成这样:
class Wpse_145991_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
//...
}
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
//...
}
}
-Notice: Undefined variable: indent
接近新类的底部
start_el() 方法您将看到该行
$output .= $indent . \'<li class="nav-main-item">\';
但是
$indent 从未在方法中定义。
Walker 课程倾向于设置
$indent 用于将HTML空白格式化为计数的变量
$depth 制表符。这与功能无关,但可以通过定义
$indent 在上述行之前的某处:
$indent = str_repeat("\\t", $depth);
此时,问题中发布的实现应该生成一个菜单,而不会抛出任何错误或警告。
当Walker_Nav_Menu 是walk()ing,两个start_el() 和start_lvl() 方法传递了$depth 可被视为代表“级别”、“子菜单”或<ul> 当前项和数据根(即顶层)之间的元素<ul> 要素

通过在此基础上有条件地分支来实现$depth, 您可以为不同的元素分配不同的类&;级别。例如,使用switch 允许您为每个项目和级别微调类:
class Wpse_145991_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\\t", $depth );
// Select a CSS class for this `<ul>` based on $depth
switch( $depth ) {
case 0:
// Top-level submenus get the \'nav-main-sub-list\' class
$class = \'nav-main-sub-list\';
break;
case 1:
case 2:
case 3:
// Submenus nested 1-3 levels deep get the \'nav-other-sub-list\' class
$class = \'nav-other-sub-list\';
break;
default:
// All other submenu `<ul>`s receive no class
break;
}
// Only print out the \'class\' attribute if a class has been assigned
if( isset( $class ) )
$output .= "\\n$indent<ul class=\\"$class\\">\\n";
else
$output .= "\\n$indent<ul>\\n";
}
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = str_repeat("\\t", $depth);
$attributes = \'\';
! empty ( $item->attr_title )
// Avoid redundant titles
and $item->attr_title !== $item->title
and $attributes .= \' title="\' . esc_attr( $item->attr_title ) .\'"\';
! empty ( $item->url )
and $attributes .= \' href="\' . esc_attr( $item->url ) .\'"\';
$attributes = trim( $attributes );
$title = apply_filters( \'the_title\', $item->title, $item->ID );
$item_output = "$args->before<a $attributes>$args->link_before$title</a>"
. "$args->link_after$args->after";
// Select a CSS class for this `<li>` based on $depth
switch( $depth ) {
case 0:
// Top-level `<li>`s get the \'nav-main-item\' class
$class = \'nav-main-item\';
break;
default:
// All other `<li>`s receive no class
break;
}
// Only print out the \'class\' attribute if a class has been assigned
if( isset( $class ) )
$output .= $indent . \'<li class="\'. $class . \'">\';
else
$output .= $indent \'<li>\';
$output .= apply_filters(
\'walker_nav_menu_start_el\',
$item_output,
$item,
$depth,
$args
);
}
}