缩略图

WordPress如何在父分类获取所有子分类/二级分类

2026年09月27日 网站文章 会被自动插入 会被自动插入
本文最后更新于2026-09-27已经过去了7天请注意内容时效性
热度6 点赞 收藏0 评论0

在我们开发WordPress主题的过程中,如果有一个需求是要获取到父分类的所有子分类,该怎么实现呢?

其实这个需求是很简单的,几行代码就可以搞定。

今天90资源网给大家带来一个小小的wordpress教程,如何在父分类获取所有子分类/二级分类。

首先在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号  
}

使用方法

将下面代码放在需要用到子分类的父分类即可

<?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
    )); 
?>

更多技术教程,请关注90资源网www.cnhacker90.com

淚
奈
硫
正文结束 阅读本文相关话题
相关阅读
评论框
正在回复
评论列表

暂时还没有任何评论,快去发表第一条评论吧~

空白列表