1.现在function.php里面添加下面的代码
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号
}
2.然后在页面要显示二级分类的地方粘贴下面这段代码即可
<?php
if(is_single()||is_category())
{
if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" )
{
echo '<ul>';
echo wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC");
echo '</ul>';
}
}
?>
孙级分类用介个:
<?php wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li="); ?>
wp_list_cats(“child_of=” . get_category_root_id($cat) . “&depth=0&hide_empty=0″)
‘show_option_all’ => “, 无链接的分类 ‘orderby’ => ‘name’, 按照分类名排序 ‘order’=> ‘ASC’, 升序 ‘show_last_update’ => 0, 不显示分类中日志的最新时间戳 ‘style’ => ‘list’, 用列表显示分类 ‘show_count’ => 0, 0, 不显示分类下的日志数 ‘hide_empty’ => 1, Displays only Categories with posts ‘use_desc_for_title’ => 1, 显示分类链接中 title 标签的分类描述 ‘child_of’ => 0, 子分类无限制 ‘feed’ => ”, 无 feed ‘feed_image’ => ”, 无 feed 图片显示 ‘exclude’ => ”, 不在分类列表中显示该分类 ‘hierarchical’ => true, 分层显示父/子分类 ‘title_li’ => __(‘Categories’), 在列表前作为标题显示分类 ‘echo’ => 1 显示分类
延伸一下,调取父级页面的子页面:
<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) {
echo '<ul>';
echo $children;
echo '</ul>';
} ?>
再延伸一下,在 Single.php 页面获取当前文章所属分类的一级分类的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号
}
function get_article_category_ID() {
$category = get_the_category();
return $category[0]->cat_ID;
}
在 Single.php 页面这样调用:
<?php echo get_category_root_id(get_article_category_ID()); ?>
感谢:
http://www.l1gc.com/wordpress%E5%A6%82%E4%BD%95%E6%98%BE%E7%A4%BA%E9%A1%B6%E7%BA%A7%E7%88%B6%E7%B1%BB%E7%9A%84%E5%AD%90%E7%B1%BB%E3%80%81%E5%BD%93%E5%89%8D%E6%96%87%E7%AB%A0%E7%88%B6%E7%B1%BB%E7%9A%84%E5%AD%90%E5%88%86-2/
http://mengqing.org/archives/get-root-cat-id.html
WordPress 怎么获取当前分类的子分类?
先在 functions.php 里定义 get_category_root_id(),通过 category_parent 一层层向上找到根分类。然后在分类页或文章页里用 wp_list_categories('child_of=根分类ID&depth=0&hide_empty=0…') 输出子分类列表即可。
单篇文章里怎么拿到所属一级分类ID?
先用 get_the_category() 取出文章分类,再结合 get_category_root_id() 把当前分类向上追到顶层分类。这样得到的就是文章所属一级分类 ID,适合在 Single.php 里做导航高亮或分类展示。
父级页面的子页面列表怎么调出来?
判断当前页面是否有 post_parent:有父级就用 child_of=父级ID,没有父级就用 child_of=当前页面ID,再把 wp_list_pages 的结果缓存到变量里。最后判断变量是否为空,非空时包一层 ul 输出。







发表回复