問題描述
我正在嘗試建立一個最多顯示 5 個專案的選單。如果有更多的專案,它應該將它們包裝到另一個<ul> 元素中以建立一個下拉式清單。
5 件以內:
6 項以上
我知道這樣的功能可以很容易地被建立與一個步行者計數的選單項和包裹,如果有多達 5 個重新分配到一個單獨的<ul> 。但我不知道如何建立這個步行者。
現在顯示我的選單的程式碼如下:
<?php wp_nav_menu( array( 'theme_location' => 'navigation', 'fallback_cb' => 'custom_menu', 'walker' =>new Custom_Walker_Nav_Menu ) ); ?>
我注意到,如果選單沒有被使用者定義,並且它使用回退函式,而是 Walker 沒有任何效果。我需要它在兩種情況下工作。
最佳解決方案
使用自定義 Walker,start_el()方法可以訪問 $depth 引數:當 0 是 0 時,elemnt 是頂級的,我們可以使用此資訊來維護一個內部計數器。
當計數器達到極限時,我們可以使用 DOMDocument 從完整的 HTML 輸出中獲取最後新增的元素,將其包裝在子選單中並將其重新新增到 HTML 。
Edit
當元素的數量正好是我們需要的數量+ 1,例如我們要求 5 個元素可見,選單有 6 個,分割選單是沒有意義的,因為元素將是 6 。程式碼被編輯以解決這個問題。
以下是程式碼:
class SplitMenuWalker extends Walker_Nav_Menu {
private $split_at;
private $button;
private $count = 0;
private $wrappedOutput;
private $replaceTarget;
private $wrapped = false;
private $toSplit = false;
public function __construct($split_at = 5, $button = '<a href="#">…</a>') {
$this->split_at = $split_at;
$this->button = $button;
}
public function walk($elements, $max_depth) {
$args = array_slice(func_get_args(), 2);
$output = parent::walk($elements, $max_depth, reset($args));
return $this->toSplit ? $output.'</ul></li>' : $output;
}
public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$this->count += $depth === 0 ? 1 : 0;
parent::start_el($output, $item, $depth, $args, $id);
if (($this->count === $this->split_at) && ! $this->wrapped) {
// split at number has been reached generate and store wrapped output
$this->wrapped = true;
$this->replaceTarget = $output;
$this->wrappedOutput = $this->wrappedOutput($output);
} elseif(($this->count === $this->split_at + 1) && ! $this->toSplit) {
// split at number has been exceeded, replace regular with wrapped output
$this->toSplit = true;
$output = str_replace($this->replaceTarget, $this->wrappedOutput, $output);
}
}
private function wrappedOutput($output) {
$dom = new DOMDocument;
$dom->loadHTML($output.'</li>');
$lis = $dom->getElementsByTagName('li');
$last = trim(substr($dom->saveHTML($lis->item($lis->length-1)), 0, -5));
// remove last li
$wrappedOutput = substr(trim($output), 0, -1 * strlen($last));
$classes = array(
'menu-item',
'menu-item-type-custom',
'menu-item-object-custom',
'menu-item-has-children',
'menu-item-split-wrapper'
);
// add wrap li element
$wrappedOutput .= '<li class="'.implode(' ', $classes).'">';
// add the "more" link
$wrappedOutput .= $this->button;
// add the last item wrapped in a submenu and return
return $wrappedOutput . '<ul class="sub-menu">'. $last;
}
}
用法很簡單:
// by default make visible 5 elements
wp_nav_menu(array('menu' => 'my_menu', 'walker' => new SplitMenuWalker()));
// let's make visible 2 elements
wp_nav_menu(array('menu' => 'another_menu', 'walker' => new SplitMenuWalker(2)));
// customize the link to click/over to see wrapped items
wp_nav_menu(array(
'menu' => 'another_menu',
'walker' => new SplitMenuWalker(5, '<a href="#">more...</a>')
));
次佳解決方案
甚至有一種方法可以使 CSS 成為可能。這有一些限制,但我仍然認為這可能是一個有趣的方法:
Limitations
-
你需要硬編碼下拉式清單的寬度
-
Browser-Support 。你基本上需要 CSS3 selectors 。但是從 IE8 起的一切都應該起作用,儘管我還沒有測試過。
-
這更是一個 proof-of-concept 。有幾個缺點,如僅在沒有 sub-items 的情況下工作。
Approach
雖然我沒有真正使用”Quantity Queries” :nth-child 和~的創意使用我已經閱讀在最近的 Quantity Queries for CSS 是什麼導致我的這個解決方案。
方法基本上是這樣的:
-
在第 4 之後隱藏所有的專案
-
使用
beforepseudo-element 加入...點。 -
當懸停點 (或任何隱藏的元素) 時,會顯示額外的專案 aka 子選單。
以下是預設 WordPress 選單標記的 CSS 程式碼。我已經線上評論。
/* Optional: Center the navigation */
.main-navigation {
text-align: center;
}
.menu-main-menu-container {
display: inline-block;
}
/* Float menu items */
.nav-menu li {
float:left;
list-style-type: none;
}
/* Pull the 5th menu item to the left a bit so that there isn't too
much space between item 4 and ... */
.nav-menu li:nth-child(4) {
margin-right: -60px;
}
/* Create a pseudo element for ... and force line break afterwards
(Hint: Use a symbol font to improve styling) */
.nav-menu li:nth-child(5):before {
content: "...A";
white-space: pre;
}
/* Give the first 4 items some padding and push them in front of the submenu */
.nav-menu li:nth-child(-n+4) {
padding-right: 15px;
position: relative;
z-index: 1;
}
/* Float dropdown-items to the right. Hardcode width of dropdown. */
.nav-menu li:nth-child(n+5) {
float:right;
clear: right;
width: 150px;
}
/* Float Links in dropdown to the right and hide by default */
.nav-menu li:nth-child(n+5) a{
display: none;
float: right;
clear: right;
}
/* When hovering the menu, show all menu items from the 5th on */
.nav-menu:hover li:nth-child(n+5) a,
.nav-menu:hover li:nth-child(n+5) ~ li a{
display: inherit;
}
/* When hovering one of the first 4 items, hide all items after it
so we do not activate the dropdown on the first 4 items */
.nav-menu li:nth-child(-n+4):hover ~ li:nth-child(n+5) a{
display: none;
}
我還建立了一個 jsfiddle 來顯示它:http://jsfiddle.net/jg6pLfd1/
如果您有任何進一步的問題如何工作,請發表評論,我很樂意進一步澄清程式碼。
第三種解決方案
您可以使用 wp_nav_menu_items 過濾器。它接受選單輸出和儲存選單屬性的引數,如選單,容器等。
add_filter('wp_nav_menu_items', 'wpse_180221_nav_menu_items', 20, 2);
function wpse_180221_nav_menu_items($items, $args) {
if ($args->menu != 'my-menu-slug') {
return $items;
}
// extract all <li></li> elements from menu output
preg_match_all('/<li[^>]*>.*?</li>/iU', $items, $matches);
// if menu has less the 5 items, just do nothing
if (! isset($matches[0][5])) {
return $items;
}
// add <ul> after 5th item (can be any number - can use e.g. site-wide variable)
$matches[0][5] = '<li class="menu-item menu-item-type-custom">…<ul>'
. $matches[0][5];
// $matches contain multidimensional array
// first (and only) item is found matches array
return implode('', $matches[0]) . '</ul></li>';
}
第四種方案
有一個工作的功能,但不知道是否是最好的解決方案。
我使用了一個自定義步行器:
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "t", $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
/**
* This counts the $menu_items and wraps if there are more then 5 items the
* remaining items into an extra <ul>
*/
global $menu_items;
$menu_items = substr_count($output,'<li');
if ($menu_items == 4) {
$output .= '<li class="tooltip"><span>...</span><ul class="tooltip-menu">';
}
$output .= $indent . '<li' . $id . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
顯示實際選單的功能如下:
<?php
wp_nav_menu( array( 'container' => false, 'theme_location' => 'navigation', 'fallback_cb' => 'custom_menu', 'walker' =>new Custom_Walker_Nav_Menu ) );
global $menu_items;
// This adds the closing </li> and </ul> if there are more then 4 items in the menu
if ($menu_items > 4) {
echo "</li></ul>";
}
?>
我宣佈全域性變數 $ menu_items 並用它來顯示關閉<li> 和<ul> 標籤。在自定義步行者中也可能做到這一點,但是我沒有發現在哪裡和如何。
兩個問題:1. 如果在選單中只有 5 個專案,它將最後一個專案也包含在一個雖然沒有必要。
-
如果使用者實際上已經為 theme_location 分配了一個選單,則該功能正常工作,如果 wp_nav_menu 顯示回退功能,則 Walker 不會啟動
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。

