在Wordpress中更改子菜单换行

时间:2016-08-22 22:21:52

标签: php wordpress

在Wordpress中,如何使用wp_nav_menu在所有子菜单中添加按钮或div?

这是我目前的代码:

<?php wp_nav_menu(array(
  'theme_location' => 'main_menu', 
  'items_wrap'=>'%3$s', 
  'container' => false
)); ?>

这是我想要的输出:

<li class="submenu">
  <a>Link 1</a>
  <ul>
    <li><a>Link 2</a></li>
  </ul>
  <button type="button">Click Me!</button> 
</li>

1 个答案:

答案 0 :(得分:1)

所以,Custom Walkers使用起来有点痛苦,直到你理解它们为止。

以下自定义助行器代码可以为您提供所需的信息。将其添加到主题的functions.php文件中:

class Custom_Button_Walker extends Walker_Nav_Menu {
    // We only care about the "end level" part of the menu, where closing </ul> tags are generated
    public function end_lvl( &$output, $depth = 0, $args = array() ) {
        // This is from WP core code
        $indent = str_repeat("\t", $depth);
        // This line ensures we only add it on the proper level
        $button = (0 == $depth) ? "{$indent}<button type=\"button\">Click Me!</button>\n" : '';
        // This line is modified to include the button markup
        $output .= "{$indent}</ul>\n{$button}";
    }
}

要使用自定义助行器,请按以下方式修改wp_nav_menu来电:

wp_nav_menu( array(
    'theme_location' => 'main_menu', 
    'items_wrap'     =>'%3$s', 
    'container'      => FALSE,
    'walker'         => new Custom_Button_Walker()
));