php - 更改 Wordpress 中的子菜单换行

标签 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>

最佳答案

所以,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()
));

关于php - 更改 Wordpress 中的子菜单换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39089597/

相关文章:

php - 不使用 scandir() 或 readdir 映射文件系统

php - 在实体库或任何地方访问 Symfony 配置参数

session 启动失败后 PHP 重定向

PHP编译: off_t undefined

php - PHP 脏话过滤器的实现

php - 如何在新订单 WooCommerce 电子邮件通知中将 "Product"更改为 "Service"

wordpress - wordpress(前端)中的 Dashicons 不会显示

wordpress - 带有部分工作树的 Git 后接收 Hook

php - 如何在 Wordpress 中添加对评论的回复

css - 如何删除侧面板和主体内容周围的边框线?