在使用 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');?>