在开发[吃货](https://api.salongweb.com/portfolio/chihuo.html)主题Chihuo时，要对产品和文章进行筛选，在一级分类下显示所有一级分类和当前一级分类下的所有二级分类，在二级分类下，显示所有一级分类和当前二级分类下的所有三级分类，依次按级显示分类。分类级别的判断稍复杂，判断当前分类属于一个什么层级，通过获取顶级分类和当前分类ID来判断，当前分类ID是否等于顶级分类，当前分类是否有子分类等条件来判断，所以顶级分类的判断是相当重要。

### 添加如下代码到主题functions.php文件中：

1. //获取顶级分类ID
2. function salong\_category\_top\_parent\_id ($current\_cat\_ID) {
3. while ($current\_cat\_ID) {
4. $cat = get\_category($current\_cat\_ID); // get the object for the catid
5. $current\_cat\_ID = $cat-&gt;category\_parent; // assign parent ID (if exists) to $current\_cat\_ID
6. // the while loop will continue whilst there is a $current\_cat\_ID
7. // when there is no longer a parent $current\_cat\_ID will be NULL so we can assign our $catParent
8. $catParent = $cat-&gt;cat\_ID;
9. }
10. return $catParent;
11. }

### 获取顶级分类ID：

1. echo salong\_category\_top\_parent\_id ($current\_cat\_ID);

`$current_cat_ID`为当前分类的ID，在调用此代码的文件中需要获取。

分类级别的判断暂不知道WordPress有没有这样的函数，不过通过当前代码就可以很方便的来判断分类的层级。