wordpress 自定义菜单

有时候我们需要在菜单里加入额外的一些元素,可以用Walker_Nav_Menu类来完成。

class description_walker extends Walker_Nav_Menu {   function start_el(&$output, $item, $depth, $args) {   global $wp_query;   global $wpdb;   $indent = ( $depth ) ? str_repeat( "t", $depth ) : '';      $class_names = $value = '';      $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 ) );   $class_names = ' class="' . esc_attr( $class_names ) . '"';      $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );   $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';      $output .= $indent . '<li' . $id . $value . $class_names .'>';      $prepend = '';   $append = '';   $description = ! empty( $item->attr_title ) ? '' . esc_attr( $item->attr_title ) . '' : '';      if($depth != 0) {   $description = $append = $prepend = "";   $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';   }   $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';   $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';   $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';      $item_output = $args->before;   $item_output .= '<a'. $attributes .'><i class="'.$description.'"></i>';   $item_output .= $args->link_before . $prepend . apply_filters( 'the_title', $item->title, $item->ID ) . $append;   $item_output .= $args->link_after;      $has_children = $wpdb -> get_var( "SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'" );   if ($has_children > 0) { //如果有二级菜单   $item_output .= '<span class="arrow"></span>';   }   $item_output .= '</a>';   $item_output .= $args->after;      $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );   }  }

给当前菜单添加class

function special_nav_class($classes, $item){   if( in_array('current-menu-item', $classes) || in_array('current-menu-ancestor', $classes) || in_array('current-post-parent', $classes) || in_array('current-post-ancestor', $classes)){   $classes[] = 'active ';   }   return $classes;  }  add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

来源地址:wordpress 自定义菜单

转载声明:本站文章若无特别说明,皆为原创,转载请注明来源:www.88531.cn资享网,谢谢!^^

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享