2016-08-22 52 views
2

在Wordpress中,如何使用wp_nav_menu將按鈕或div添加到所有子菜單中?在Wordpress中更改子菜單換行

這是我當前的代碼:

<?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> 
+0

你將有可能創建自己的[菜單沃克類](HTTPS: //www.smashingmagazine.com/2015/10/customize-tree-like-data-structures-wordpress-walker-class/)。你所要求的並不是一項簡單的任務。 –

回答

1

所以,Custom Walkers是一個有點痛一起工作,直到你瞭解他們。

下面的自定義walker代碼應該爲你提供你所需要的。添加到您的主題的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() 
)); 
+0

哇,謝謝。驚訝它是如此複雜,我習慣於TYPO3自定義菜單很容易。 1個問題:我如何製作它,以便適用於1級和2級?我有一個3層菜單... – user500665

+1

如果你想要它適用於所有的深度,改變線來簡單閱讀'$ button =「{$ indent} \ N「;' –