我正在使用自定義Walker function來自定義Wordpress中菜單的顯示。獲取wp_nav_menu元素的兄弟的數量
爲了向前邁進一步,我想爲超過X個元素的子菜單使用不同的HTML標記。
有沒有一種方法可以檢查給定項目的元素數量start_el
函數中的沃克Walker_Nav_Menu
?
我正在使用自定義Walker function來自定義Wordpress中菜單的顯示。獲取wp_nav_menu元素的兄弟的數量
爲了向前邁進一步,我想爲超過X個元素的子菜單使用不同的HTML標記。
有沒有一種方法可以檢查給定項目的元素數量start_el
函數中的沃克Walker_Nav_Menu
?
它不使用沃克類最簡單的事情,所以我想到了一個解決方案的使用DOMDocument解析菜單HTML和菜單已建成之後算子菜單兒童(使用wp_nav_menu_{$menu->slug}_items
過濾器):
add_filter('wp_nav_menu_{MENU_SLUG}_items', function($items, $args) {
$dom = new DOMDocument();
$dom->loadHTML($items);
// get the .sub-menu elements
$submenus = $dom->getElementsByTagName('ul');
// for each one if it has children add a class
// like has-{num}-children
foreach ($submenus as $ul) {
if($ul->hasChildNodes()) {
// number of child nodes divided by 2
// to exclude the text nodes
$numChildren = $ul->childNodes->length/2;
$class = "has-$numChildren-children";
$ul->setAttribute(
'class', $ul->getAttribute('class') . ' ' . $class
);
}
}
// save the changes
$html = $dom->saveHtml($dom->documentElement);
// remove html and body tags added by $dom->loadHTML
$items = preg_replace('~</?(html|body)>~', '', $html);
return $items;
}, 10, 2);
這應該添加一個類has-{num}-children
與每個子菜單與兒童(其中{num}
是兒童的人數),以便您可以針對任何你想要的。
它可以很容易地更改爲僅適用於具有最少子女人數的子菜單。
記得用你的菜單slu change更改{MENU_SLUG}
。
我認爲你將不得不這樣做與jQuery – mdarmanin