在後台菜單設置頁面,每個菜單項默認有 6 個或 7 個屬性,如下圖,其中有一項圖像描述,一般的主題基本用不到這個,而且這個屬性也是被隱藏了,至今阿樹也沒有用過,但是既然 WordPress 提供了這個屬性,那麼他的用處以及用法如何?作為一系列教程,還是有必要寫一下。

注意:本篇教程中代碼參考自:http://www.wpbeginner.com/wp-themes/how-to-add-menu-descriptions-in-your-WordPress-themes/
一、顯示圖像描述項
在後台菜單設置頁面,點擊頁面右上角的--「顯示選項」,勾選裏面的--「圖像描述」,然後每個菜單項中都會出現這個圖像描述字段的輸入框。

然後你可以為每個菜單項輸入描述信息了,不過默認情況下,主題是不會顯示菜單的描述信息的,要想顯示這個描述信息,還需要一些步驟。

二、通過 walker 參數來改變輸出
和上一篇教程一樣,在主題中添加下面的類:
- class Menu_With_Description extends Walker_Nav_Menu {
- function start_el(&$output, $item, $depth, $args) {
- global $wp_query;
- $indent = ( $depth ) ? str_repeat( " ", $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;
- $item_output .= '<br /><span class="sub">' . $item->description . '</span>';
- $item_output .= '</a>';
- $item_output .= $args->after;
- $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
- }
- }
三、前台調用設置 walker 參數。
- <?php
- $args = array(
- 'walker' => new Menu_With_Description(), //注意是 new Menu_With_Description();
- 'theme_location' => 'ashu-menu',
- );
- wp_nav_menu($args);
- ?>
四、實際效果,阿樹用 twentyten 主題測試:

五、美化。