在製作 WordPress 主題的時候經常遇到怎麼在 WordPress 分類頁顯示當前分類下的子分類或者在文章頁顯示所屬分類的子分類這樣的問題, 尤其在做中文企業主題的時候必須要用到這個技巧的。今天和大家分享之前我做企業主題時調用子分類的函數。
1. 現在 function.php 裏面添加下面的代碼
function
get_category_root_id($cat){$this_category = get_category($cat); //
取得當前分類 while($this_category->category_parent) //
若當前分類有上級分類時, 循環 {$this_category =
get_category($this_category->category_parent); //
將當前分類設為上級分類 (往上爬)}return $this_category->term_id; // 返回根分類的 id 號}
2. 然後在頁面要顯示二級分類的地方粘貼下面這段代碼即可
<?phpif(is_single()||is_category()){if(get_category_children(get_category_root_id(the_category_ID(false)))!=
"" ){echo '<ul>';echo
wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)).
"&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC");echo
'</ul>';}}?>
這個函數的功能就是在分類頁和文章頁顯示當前分類的子分類 (二級分類) 。