問題描述
我在 wp_nav_menu 功能中使用以下內容建立一個選擇下拉選單,其中每個選單項是選擇下拉式清單中的一個選項…
'items_wrap' => '<select>%3$s</select>'
'before' => '<option value="">'
'after' => '</option>'
如何在'before'宣告中新增連結值?有沒有更好的方法來解決這個問題?我知道 wp_dropdown_pages,但是這不起作用,因為我希望使用者能夠從”Menus” 頁面控制選單。
最佳解決方案
您無法使用 wp_nav_menu 執行此操作,因為它會輸出列表項,並且您將使用程式碼生成無效的標記。
嘗試使用 wp_get_nav_menu_items()代替。
使用自定義步行器的下拉選單的快速解決方案:
class Walker_Nav_Menu_Dropdown extends Walker_Nav_Menu{
// don't output children opening tag (`<ul>`)
public function start_lvl(&$output, $depth){}
// don't output children closing tag
public function end_lvl(&$output, $depth){}
public function start_el(&$output, $item, $depth, $args){
// add spacing to the title based on the current depth
$item->title = str_repeat(" ", $depth * 4) . $item->title;
// call the prototype and replace the <li> tag
// from the generated markup...
parent::start_el(&$output, $item, $depth, $args);
$output = str_replace('<li', '<option', $output);
}
// replace closing </li> with the closing option tag
public function end_el(&$output, $item, $depth){
$output .= "</option>n";
}
}
在你的模板中使用它像這樣:
wp_nav_menu(array(
'theme_location' => 'primary', // your theme location here
'walker' => new Walker_Nav_Menu_Dropdown(),
'items_wrap' => '<select>%3$s</select>',
));
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。