在企業網站製作時,需要在網站的邊欄列出企業產品分類,如果公司網站產品專案很多的情況,就需要設定二級分類和子分類,如何在建網站時顯示當前分類下的子分類或者在文章頁顯示所屬分類的子分類這樣的問題,尤其在做中文企業主題的時候必須要用到這個技巧的。

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. 然後在頁面要顯示二級分類的地方貼上下面這段程式碼即可

<?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>』;
}
}
?>