在使用 WordPress 建網站時,往往需要在側邊欄調用當前欄目的子分類子目錄,而且在點擊子目錄時,還會側邊欄顯示這些子目錄的分類。

在 wp 程序下,不同分類調用自己的子分類,子目錄的方法如下:

  1. 將以下的函數代碼複製,粘貼到自己的網站的模板的 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. 在網站上需要調用子目錄子分類的地方,用以下的代碼來調用。 (以下代碼的作用:通過 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');?>