doushan6161 2016-08-22 22:21
浏览 102
已采纳

在Wordpress中更改子菜单换行

In Wordpress, how can I add a button or div into all sub-menu li's using wp_nav_menu?

This is my current code:

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

This is my desired output:

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

1条回答 默认 最新

  • du1913 2016-08-22 22:56
    关注

    So, Custom Walkers are a bit of a pain to work with, until you understand them.

    The below custom walker code should get you what you need. Add this to your theme's functions.php file:

    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>
    " : '';
            // This line is modified to include the button markup
            $output .= "{$indent}</ul>
    {$button}";
        }
    }
    

    To use the custom walker, modify your wp_nav_menu call like so:

    wp_nav_menu( array(
        'theme_location' => 'main_menu', 
        'items_wrap'     =>'%3$s', 
        'container'      => FALSE,
        'walker'         => new Custom_Button_Walker()
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?