How to show the description in the menu and allow html #2
-
This is a follow up to the thread How to show the description of the menu
Here is an improved version (with thanks to dennis.winter for the original version I based this on)
//improve menu output and allow descriptions class My_Walker extends Walker_Nav_Menu { function start_el(&$output, $item, $depth, $args) { global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names = ' class="' . esc_attr( $class_names ) . '"'; $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>'; $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 .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; if (strlen($item->description)>2) { $item_output .= '<br /><span class="sub">' . $item->description . '</span></a>'; } else { $item_output .= '</a>'; } $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } //strip sanitizers from menu description remove_filter('nav_menu_description', 'strip_tags');
The original version added a span called ‘sub’ to all the menu items even if they did not have a description, this new version uses
if (strlen($item->description)>2) { $item_output .= '<br /><span class="sub">' . $item->description . '</span></a>'; } else { $item_output .= '</a>'; }
to check the description string, if it is less than one character it ignores the code to add it. One character is always counted by default which is why there is a >2 there.
As a bonus i’ve added
remove_filter('nav_menu_description', 'strip_tags');
This allows you to add html to your menu item descriptions like line breaks and divs etc. I would be very careful adding links though as they will break the menu structure.
Hope this helps anyone who had the same issues as me!
- The topic ‘How to show the description in the menu and allow html #2’ is closed to new replies.