# 輸入當前頂級分類的子分類
> 使用wordpress建網站時,在側邊欄往往需要調用某個當前頂級分類下的子分類,這樣只要在網站后臺添加分類后,網站界面就會自動的調用顯示出來。
> 本內容來自網絡分享,以下為原文鏈接:
> @link [https://www.xuewangzhan.net/wpbbs/6770.html](https://www.xuewangzhan.net/wpbbs/6770.html)

## 在function.php中加入如下代碼:
```
/**
* 獲取當前欄目的頂級欄目。
* 獲取當前頂級分類下的子分類。
*
* @link https://blog.csdn.net/weixin_33985507/article/details/91900600
* @link https://www.seo628.com/2547.html
*
* 用法實例
* <?php
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>';
}
?>
*
*/
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號
}
```
## 實際運用舉例(在邊欄sidabar.php中加入如下代碼)
```
<?php
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>';
}
?>
```