WordPress Menu Walker-帮助为每个子菜单添加自定义类

时间:2020-05-20 作者:Pikk

我正在尝试将walker应用到我已经存在的菜单中,以便向每个子菜单锚定标记添加自定义类。

这是我的菜单:

            wp_nav_menu(array(
            \'theme_location\' => \'menu-top\',
            \'container\'      => \'ul\',
            \'menu_class\'     => \'header_nav_ul\',
            \'menu_id\'        => \'header_nav_id\',
            \'depth\'          => 0,
        ))
我添加了wolder,它变成:

wp_nav_menu(array(
            \'theme_location\' => \'menu-top\',
            \'container\'      => \'ul\',
            \'menu_class\'     => \'header_nav_ul\',
            \'menu_id\'        => \'header_nav_id\',
            \'depth\'          => 0,
            \'walker\'        => new my_walker_nav_menu_start_el(),
        ))
walker函数如下:

function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
        // you can put your if statements in here (use item, depth and args in conditions)
        if ( $depth == 1 ) {
            $item_output = preg_replace(\'/<a /\', \'<a class="level-1-menu" \', $item_output, 1);
        } else if ( $depth == 2 ){
            $item_output = preg_replace(\'/<a /\', \'<a class="level-2-menu" \', $item_output, 1);
        }
        // .. and so on
        return $item_output;
    }
    add_filter(\'walker_nav_menu_start_el\', \'my_walker_nav_menu_start_el\', 10, 4);
然而,开箱即用的方法是行不通的。我是php新手,但我发现它是new walker 这建议我应该将该函数作为一个类来编写。

有人能帮我编辑我的功能,这样它就可以很好地与我的菜单配合使用了吗?

非常感谢。

1 个回复
SO网友:WebElaine

你说得对,是面向对象的部分把你甩了。

导航菜单调用应为:

wp_nav_menu(array(
    \'theme_location\' => \'menu-top\',
    \'container\'      => \'ul\',
    \'menu_class\'     => \'header_nav_ul\',
    \'menu_id\'        => \'header_nav_id\',
    \'depth\'          => 0,
    \'walker\'         => new my_walker_nav_menu_start_el,
));
步行者姓名后无括号()助行器本身需要扩展核心Walker_Nav_Menu, 而且没有add_filter() 要求它。

// Extend the existing Core class, to build on its functionality
class my_walker_nav_menu_start_el extends Walker_Nav_Menu {
    // Make the function public so it can be called elsewhere
    public function start_el($item_output, $item, $depth = 0, $args = array(), $id = 0) {
        if ( $depth == 1 ) {
            $item_output = preg_replace(\'/<a /\', \'<a class="level-1-menu" \', $item_output, 1);
        } else if ( $depth == 2 ) {
            $item_output = preg_replace(\'/<a /\', \'<a class="level-2-menu" \', $item_output, 1);
        }
        return $item_output;
    }
}
// Remove the add_filter() call as it\'s not used
只要确保链接没有任何其他类,否则您将得到具有2个“class”属性的链接。