在製作 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;
- }
2. 然後在頁面要顯示二級分類的地方粘貼下面這段代碼即可
- <?php
- if(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>';
- }
- ?>
這個函數的功能就是在分類頁和文章頁顯示當前分類的子分類 (二級分類) 。