WordPress获取当前分类下的所有子分类
这是一条文章内容页公告,可在后台开启或关闭,此处可使用html标签...
在WordPress获取父分类是比较常见的,今天给大家讲讲怎么获取父分类的所有子分类。
其实也很简单,主要用到这个函数:wp_list_categories(),不过在用函数之前需要添加一段代码:
//父分类获取所有子分类
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号
}
把上面代码添加到主题的 functions.php 文件最下,然后在需要获取父分类的所有子分类的地方使用下面代码:
<?php wp_list_categories(
$args = array(
'show_option_all' => '',
'orderby' => 'name',
'use_desc_for_title' => 1,
'child_of' => get_category_root_id($cat),
'optioncount'=>1,
'hierarchical' => 1,
'title_li' => '',
'show_option_none' => __('<span style="padding:0 20px;">抱歉,暂无分类。</span>'),
'depth' => 1,
'taxonomy' => 'category',
'walker' => null
));
?>
这样就可以在获取到父分类的所有子分类

UI掌控:cinui_
关注我们,获取更多的全网素材资源有趣有料!