如何在wordpress自定义菜单walker中添加或更改li类名称 [英] How do I add or change an li class name in a wordpress custom menu walker

查看:1230
本文介绍了如何在wordpress自定义菜单walker中添加或更改li类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何添加我自己的类名到我的wp_nav_menu。我有一个自定义的walker菜单设置为更改UL名称,但是如何添加一个css类到一层和两层深的li?

I'm struggling to figure out how to add my own class names to my wp_nav_menu. I have a custom walker menu set up to change a UL name, but how does one go about adding a css class to li's that are one and two levels deep?

我希望我的菜单看起来像这样:

I want my menu to look like this:

<ul>
    <li class="top_level_class">One</li>
    <li class="top_level_class">Two
        <ul>
            <li class="second_level_class">Hi</li>
        </ul>
    </li>
</ul>

我的自定义步行器看起来像这样:

My custom walker looks like this:

class My_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"nav-main-sub-list\">\n";
  }
}

但这只是换掉了UL上的类二我很困惑我如何添加类到李的一两级深。任何建议?

But that just swaps out the class on the UL two levels in. I am confused how I would add classes to the LI's one and two levels deep. Any advice?

推荐答案

您可以使用$ depth参数确定LI元素是否位于顶层或第二级UL,例如,顶层中的项目将具有0的深度,并且对于第二层具有深度1。

You can use the $depth parameter to determine if the LI element is in a top or second level UL, for example an an item in the top level will have a depth of 0, and a depth of 1 for the 2nd level.

您需要修改start_el方法。

You will need to modify the start_el method. See below, hopefully that will get you started

class My_Walker_Nav_Menu extends Walker_Nav_Menu {

   function start_lvl(&$output, $depth) {
     $indent = str_repeat("\t", $depth);
     $output .= "\n$indent<ul class=\"nav-main-sub-list\">\n";
   }

   function start_el(&$output, $item, $depth, $args) {

       ...

       if($depth == 1) {
          $class_names = ' class="second_level_class"';
       } else {
          $class_names = ' class="top_level_class"';
       }

       $output .= $indent . '<li' . $class_names . '>';

       ...

    }
}


$ b b

有关如何自定义Walker类的更多信息:
http: //wordpress.stackexchange.com/questions/116708/customizing-walker-nav-menu
http://code.tutsplus.com/tutorials/understanding-the-walker-class--wp-25401

这篇关于如何在wordpress自定义菜单walker中添加或更改li类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆