WordPress自定义Walker类,从菜单项中删除不必要的类和ID

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WordPress自定义Walker类,从菜单项中删除不必要的类和ID相关的知识,希望对你有一定的参考价值。

Could possibly be simplified to maximise efficiency. It relies on a separare WP Sleek framework function sleek_get_theme_menu_name. This could ideally be improved to allow the theme location to passed as a parameter somehow.
  1. /*-----------------------------------------------------------
  2. Custom Walker Function that only shows an active class
  3. and unique ID for each menu item, stripping out all the
  4. unnecessary classes and ID's. Nice!
  5. -----------------------------------------------------------*/
  6.  
  7. class Sleek_Walker extends Walker_Nav_Menu
  8. {
  9. function start_el(&$output,$item,$depth,$args)
  10. {
  11. global $wp_query;
  12. $indent = ($depth) ? str_repeat(' ',$depth) : '';
  13. $class_names = $value = '';
  14. $classes = empty($item->classes) ? array() : (array) $item->classes;
  15. $current_indicators = array('current-menu-item','current-menu-parent','current_page_item','current_page_parent');
  16. $newClasses = array();
  17. foreach($classes as $el)
  18. {
  19. if(in_array($el,$current_indicators))
  20. {
  21. array_push($newClasses,$el);
  22. }
  23. }
  24. $class_names = join(' ',apply_filters('nav_menu_css_class',array_filter($newClasses),$item));
  25. if($class_names != '') $class_names = ' class="active"';
  26. $itemID = strtolower($item->title);
  27. $menu_name = sleek_get_theme_menu_name('footer-menu');
  28. $output .= $indent . '<li id="' . $menu_name . '-' . $itemID . '"' . $value . $class_names .'>';
  29.  
  30. $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
  31. $attributes .= !empty($item->target) ? ' target="' . esc_attr($item->target) .'"' : '';
  32. $attributes .= !empty($item->xfn) ? ' rel="' . esc_attr($item->xfn) .'"' : '';
  33. $attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) .'"' : '';
  34.  
  35. if($depth != 0)
  36. {
  37. //children stuff, maybe you'd like to store the submenu's somewhere?
  38. }
  39.  
  40. $item_output = $args->before;
  41. $item_output .= '<a'. $attributes .'>';
  42. $item_output .= $args->link_before .apply_filters('the_title',$item->title, $item->ID);
  43. $item_output .= '</a>';
  44. $item_output .= $args->after;
  45.  
  46. $output .= apply_filters('walker_nav_menu_start_el',$item_output,$item,$depth,$args);
  47. }
  48. }

以上是关于WordPress自定义Walker类,从菜单项中删除不必要的类和ID的主要内容,如果未能解决你的问题,请参考以下文章

需要将“活动”类添加到自定义 WordPress 导航菜单

php Wordpress菜单/导航----将.active类添加到活动菜单项---- Bootstrap Nav Walker

添加一个 div 并使用 wordpress walker 更改类或导航菜单?

在我的WordPress菜单项中添加#无法正常工作

php Wordpress自定义自定义菜单类

将自定义类添加到 WordPress 导航中的锚标记