在使用WordPress建網站時,往往需要在側邊欄呼叫當前欄目的子分類子目錄,而且在點選子目錄時,還會側邊欄顯示這些子目錄的分類。
在wp程式下,不同分類呼叫自己的子分類,子目錄的方法如下:
- 將以下的函式程式碼複製,貼上到自己的網站的模板的functions.php中;(以下程式碼的作用:獲取當前目錄的ID)
//獲取當前分類ID
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號
} - 在網站上需要呼叫子目錄子分類的地方,用以下的程式碼來呼叫。(以下程式碼的作用:透過wp_list_cats標籤在引數中新增child_of的值為 get_category_root_id($cat))
<?php wp_list_cats(‘child_of=’ . get_category_root_id($cat) . ‘&depth=1&hide_empty=0&hierarchical=1&optioncount=1’);?>