問題描述
我目前正在使用自定義步行器自定義 wp_nav_menu()的輸出,我正在嘗試向<a> 標籤新增附加資訊。
我想讓每個選單連結的輸出看起來像是:
<a class="boxPAGEID" href="#">About Me Page</a>
PAGEID 是我連結到的頁面的 ID 。
原因是因為我正在開發一個主題,它可以在燈箱中開啟頁面內容,這是由標籤中的類引發的。
以下是我的 functions.php 檔案中的自定義步行者的程式碼 (程式碼之後我會指向我遇到問題的區域):
class description_walker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{
global $wp_query;
$pageid = $wp_query->post->ID;
$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="http://'%20%20%20.%20'#'%20.'"' : '';
$prepend = '<strong>';
$append = '</strong>';
$description = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';
if($depth != 0)
{
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes . 'class="box' . $pageid . '"' .'>';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
if ($item->menu_order == 1) {
$classes[] = 'first';
}
}
}
最後是從 $item_output 開始的幾行。第二行是我要生成頁面 ID 的地方:
$item_output .= '<a'. $attributes . 'class="box' . $pageid . '"' .'>';
$pageid 如下:
global $wp_query;
$pageid = $wp_query->post->ID;
這給我一個固定的 ID,生成的所有連結。
或者,而不是 $pageid 我嘗試使用 $item->ID,但這給了我的選單項的 ID 。
有什麼建議麼?
最佳解決方案
頁面 ID(或物件 ID,因為選單項可以連結到任何物件) 儲存在 postmeta 表中,使用鍵_menu_item_object_id 。所以您可以使用以下程式碼獲取頁面 ID:
get_post_meta( $item->ID, '_menu_item_object_id', true );
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。