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

注意:本篇教程中程式碼參考自:http://www.wpbeginner.com/wp-themes/how-to-add-menu-descriptions-in-your-WordPress-themes/

一、顯示影像描述項

在後臺選單設定頁面,點選頁面右上角的--「顯示選項」,勾選裡面的--「影像描述」,然後每個選單項中都會出現這個影像描述欄位的輸入框。

然後你可以為每個選單項輸入描述資訊了,不過預設情況下,主題是不會顯示選單的描述資訊的,要想顯示這個描述資訊,還需要一些步驟。

二、透過 walker 引數來改變輸出

和上一篇教程一樣,在主題中新增下面的類:

  1. class Menu_With_Description extends Walker_Nav_Menu {
  2.     function start_el(&$output$item$depth$args) {
  3.         global $wp_query;
  4.         $indent = ( $depth ) ? str_repeat" "$depth ) : '';
  5.         $class_names = $value = '';
  6.         $classes = empty$item->classes ) ? array() : (array$item->classes;
  7.         $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter$classes ), $item ) );
  8.         $class_names = ' class="' . esc_attr( $class_names ) . '"';
  9.         $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
  10.         $attributes = ! empty$item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
  11.         $attributes .= ! empty$item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
  12.         $attributes .= ! empty$item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
  13.         $attributes .= ! empty$item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
  14.         $item_output = $args->before;
  15.         $item_output .= '<a'. $attributes .'>';
  16.         $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
  17.         $item_output .= '<br /><span class="sub">' . $item->description . '</span>';
  18.         $item_output .= '</a>';
  19.         $item_output .= $args->after;
  20.         $output .= apply_filters( 'walker_nav_menu_start_el', $item_output$item$depth$args );
  21.     }
  22. }

 

三、前臺呼叫設定 walker 引數。

  1. <?php
  2. $args = array(
  3.     'walker' => new Menu_With_Description(), //注意是 new Menu_With_Description();
  4.     'theme_location' => 'ashu-menu',
  5. );
  6. wp_nav_menu($args);
  7. ?>

 

四、實際效果,阿樹用 twentyten 主題測試

五、美化。