• 函数定义

    • functions.php中定义一个函数来获取当前分类的顶级分类ID。
  • 代码示例

    // 获取分类ID,函数参数是int类型为当前分类的ID
    function tx_wp_get_category_root_id($cat) {
      $this_category = get_category($cat); // 获取当前分类的对象
      // 循环往上获得父级分类ID
      while ($this_category->category_parent) {
        $this_category = get_category($this_category->category_parent);
      }
      return $this_category->term_id;
    }
  • 分类模板中的代码

    foreach (get_categories('child_of=' . tx_wp_get_category_root_id($cat)) as $cate) {
      echo '<a href="' . get_category_link($cate->term_id) . '">' . get_cat_name($cate->term_id) . '</a>';
    }