在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号 }
把上面代码添加到主题的 function.php 文件最下,然后在需要获取父分类的所有子分类的地方使用下面代码:
'',
'orderby' => 'name',
'use_desc_for_title' => 1,
'child_of' => get_category_root_id($cat),
'optioncount'=>1,
'hierarchical' => 1,
'title_li' => '',
'show_option_none' => __('抱歉,暂无分类。'),
'depth' => 1,
'taxonomy' => 'category',
'walker' => null
));
?>
这样就可以在获取到父分类的所有子分类