在製作 WordPress 主題的時候經常遇到怎麼在 WordPress 分類頁顯示當前分類下的子分類或者在文章頁顯示所屬分類的子分類這樣的問題,尤其在做中文企業主題的時候必須要用到這個技巧的。今天和大家分享之前我做企業主題時呼叫子分類的函式。

1. 現在 function.php 裡面新增下面的程式碼

  1. function get_category_root_id($cat)  
  2. $this_category = get_category($cat);   
  3. while($this_category->category_parent)   
  4. {  
  5. $this_category = get_category($this_category->category_parent);   
  6. }  
  7. return $this_category->term_id;   
  8. }  

2. 然後在頁面要顯示二級分類的地方貼上下面這段程式碼即可

  1. <?php  
  2. if(is_single()||is_category())  
  3. {  
  4. if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" )  
  5. {  
  6. echo '<ul>';  
  7. 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");  
  8. echo '</ul>';  
  9. }  
  10. ?>  

這個函式的功能就是在分類頁和文章頁顯示當前分類的子分類 (二級分類) 。