問題描述
我正在製作我的第一個自定義步行者來構建手風琴菜單。首先我用這個例子:http://bitacre.com/2025/custom-nav-menu-walker-for-wordpress-themes
有兩個功能。先用 start_lvl 然後 start_el 。
在 start_el 中,ID 由 $ item-> ID 實現。有人知道如何在 start_lvl 中做到這一點嗎?我需要提供 (周圍的較低級別的導航)ID,所以我可以觸發它在手風琴菜單中摺疊。
我想要生成的是這樣的:
<a href="#collapse2">Titel 2</a>
<ul id="collapse2">Lower Level Menu 2</ul>
<a href="#collapse3">Titel 3</a>
<ul id="collapse3">Lower Level Menu 3</ul>
我的代碼為 start_lvl 功能:
// add id's and classes to ul sub-menus
function start_lvl( &$output, $depth, $item ) {
// depth dependent classes
$indent = ( $depth > 0 ? str_repeat( "t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
$pgid = ; // How to get ID in here??
$classes = array(
'sub-menu',
( $display_depth == 1 ? 'accordion-body collapse' : '' ),
( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),
( $display_depth >=2 ? 'sub-sub-menu' : '' ),
'menu-depth-' . $display_depth
);
$ids = array(
'collapse' . $pgid
);
$class_names = implode( ' ', $classes );
$id_name = implode( ' ', $ids );
// build html
$output .= "n" . $indent . '<ul id="' . $id_name . '" class="' . $class_names . '">' . "n";
}
最佳解決方案
我只是在我的一個主題中做到這一點… 由於您在 Walker 的這個階段無法訪問 $ item 變量,所以您希望將當前項目存儲在更全面的範圍內確實有權訪問它。以下代碼將更有意義… 注意:除了相關代碼之外,我已經刪除了一切。
class ThemeTruck_Nav_Walker extends Walker_Nav_Menu {
private $curItem;
// retrieve the curItem
function start_lvl(&$output, $depth = 0, $args = array()) {
var_dump($this->curItem );
}
// store the curItem
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
$this->curItem = $item;
}
}
次佳解決方案
我有一個類似的問題,並通過在類中使用靜態變量來解決它:
static protected $menu_lvl;
然後在”display_element” 中,我增加了變量:
self::$menu_lvl++;
在我的代碼中,我在 start_lvl 函數中引用了這樣的東西:
$output .= "<ul id='level". self::$menu_lvl ."'>";
這不使用頁面 ID,但它使用可由 JavaScript 引用的 UL 語句的唯一 ID 。
BTW – 這對於嵌套的手風琴非常有用,或者使用 Bootstrap 為移動應用程序使用 Roots 主題中的可點擊的嵌套下拉列表。
第三種解決方案
您可以在 start_el 功能中使用以下過濾器,並在 start_lvl 功能中使用以下過濾器。
apply_filters( 'walker_nav_menu_start_lvl', $item_output, $item, $depth, $args->myarg=$item->title );
請讓我知道,如果它的作品。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。