wp_nav_menu change sub-menu class name?

前端 未结 13 2026
自闭症患者
自闭症患者 2020-11-28 02:44

Is there a way to change the child

    generated by WordPress itself to a custom class name?

    I know the parent

相关标签:
13条回答
  • 2020-11-28 02:48

    You don't need to extend the Walker. This will do:

    function overrideSubmenuClasses( $classes ) {
        $classes[] = 'myclass1';
        $classes[] = 'myclass2';
    
        return $classes;
    }
    add_action('nav_menu_submenu_css_class', 'overrideSubmenuClasses');
    
    0 讨论(0)
  • 2020-11-28 02:48

    I had to change:

    function start_lvl(&$output, $depth)

    to:

    function start_lvl( &$output, $depth = 0, $args = array() )

    Because I was getting an incompatibility error:

    Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl() should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth = 0, $args = Array)

    0 讨论(0)
  • 2020-11-28 02:49

    This is an old question and I'm not sure if the solution I'm going to mention was available by the time you asked, but I think it's worth mentioning. You can achieve what you want by adding a filter to nav_menu_submenu_css_class. See the example below - you can replace my-new-submenu-class by the class(es) you want:

    function my_nav_menu_submenu_css_class( $classes ) {
        $classes[] = 'my-new-submenu-class';
        return $classes;
    }
    add_filter( 'nav_menu_submenu_css_class', 'my_nav_menu_submenu_css_class' );
    
    0 讨论(0)
  • 2020-11-28 02:51

    There is no option for this, but you can extend the 'walker' object that WordPress uses to create the menu HTML. Only one method needs to be overridden:

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

    Then you just pass an instance of your walker as an argument to wp_nav_menu like so:

    'walker' => new My_Walker_Nav_Menu()
    
    0 讨论(0)
  • 2020-11-28 02:51

    To change the default "sub-menu" class name, there is simple way. You can just change it in wordpress file.

    location : www/project_name/wp-includes/nav-menu-template.php.

    open this file and at line number 49, change the name of sub-menu class with your custom class.

    Or you can also add your custom class next to sub-menu.

    Done.

    It worked for me.I used wordpress-4.4.1.

    0 讨论(0)
  • 2020-11-28 02:52

    Here's an update to what Richard did that adds a "depth" indicator. The output is level-0, level-1, level-2, etc.

    class UL_Class_Walker extends Walker_Nav_Menu {
      function start_lvl(&$output, $depth) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"level-".$depth."\">\n";
      }
    }
    
    0 讨论(0)
提交回复
热议问题