wordpress不同分類調用當前子分類,這種需求在一些企業網站中經常見到,例如進入產品中心目錄希望側邊欄顯示產品中心目錄下面的子分類,實現這種效果,我們需要通過兩步驟實現:
1、獲取當前目錄的ID或別名;
2、使用某個分類下面的子分類標簽完成調用。
以下是實現方法:
1、獲取當前目錄的ID;你需要在函數文件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號
}
2、以上代碼返回的當前目錄的ID為:get_category_root_id($cat),下一步我們只需要通過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');?>
新聞熱點
疑難解答