在制作WordPress主题Danxs的时候,往往要用到当前分类的父分类,下面我们就来说说通过当前分类的id来获取父分类id。

一、获取当前分类id

<?php the_category_ID(false) ?>

二、通过子分类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号
}

就这么简单,不过这个函数可不上可以获得父分类id,甚至祖分类id都可以获得。

感觉怎么样,快去试试吧。

Last modification:April 11th, 2020 at 09:18 pm
如果觉得我的文章对你有用,请随意赞赏