wordpress获取当前分类的顶级分类ID并调用子分类
- WordPress教程
- 2022-05-01 13:51:46
- 230
在制作一款wordpress主题的时候碰到个需求,要在一个分类里面获取当前分类的子分类列表,还要判断如果当前分类有顶级分类的话则获取顶级分类下的子分类列表。
本文就来记录一下实现过程,供大家参考。
首先在functions.php里面新建个函数获取到分类ID:
//获取分类ID,函数参数是int类型为当前分类的IDfunction 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>';}
用wordpress自带的“get_categories”函数循环出子分类列表即可。
以上两处代码即可实现wordpress获取当前分类的顶级分类ID并调用子分类的需求了。
声明:内容整理自网络,文章版权归原作者所有,旨在分享有价值的内容,文章如有侵权请联系本站删除,部分文章如未署名作者来源请联系我们及时备注,感谢您的支持。
本文链接:https://www.shunshiseo.com/WordPress/71.html
发表评论