問題描述
有沒有辦法 (除了新增自定義連結) 以新增自定義帖子型別歸檔到 WordPress 中的選單?如果使用自定義連結新增 (例如/cpt-archive-slug /),則 WordPress 不會將類 current-menu-item
應用於列表元素,這在樣式化選單時會帶來挑戰。
如果自定義連結包含整個 URL(例如 http://site.com/cpt-archive-slug/),則會新增這些類。但是,這可能不是’best practice’ 。
最佳解決方案
您最好的選擇是自定義連結與完整的 url 作為自定義帖子型別歸檔是不同形式的基於分類法的檔案 (類別,標籤,任何自定義分類法) 和基於日期的檔案,擁有自己的檔案。
次佳解決方案
我知道這是舊的,但我也有這個問題,我發現一個相當乾淨的方法來處理它是使用自定義選單步行者
class KB_Custom_Menu_Walker extends Walker_Nav_Menu {
protected static $custom_post_types = array();
public function start_el(&$output, $item, $depth=0, $args=array(), $id=0) {
if (isset( self::$custom_post_types[ $item->url ] )) {
$item->url = get_post_type_archive_link( self::$custom_post_types[$item->url] );
}
parent::start_el($output, $item, $depth, $args, $id);
}
public static function custom_post_types($type=null) {
if ($type) {
self::$custom_post_types[ '#post_type_'.$type ] = $type;
}
return self::$custom_post_types;
}
}
擁有 #post_type_album
網址的自定義連結選單項,您可以使用它:
# Where you defined your custom post type (could be anywhere anyway)
KB_Custom_Menu_Walker::custom_post_types('album');
# And display the menu
wp_nav_menu(array(
'theme_location' => 'primary-nav',
'walker' => new KB_Custom_Menu_Walker(),
));
注意:這假設你的帖子型別的 slug 和名稱是一樣的。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。