12 次查询 耗时 0.053 秒
本文共计853个字,0条留言,预计阅读时长3分钟
登录/注册
  • 首页
  • >
  • Notes
  • >
  • WordPress获取分类目录下的子目录
  • WordPress获取分类目录下的子目录

    作者:Misshylsay

    日期:2020年09月28日

    分类页获取当前分类目录子目录

    <?php 
    $cat_id=get_query_var('cat'); //获取当前分类目录ID
    wp_list_categories('depth=0&hide_empty=0&title_li=&orderby=id&order=asc&child_of='.$cat_id.''); ?>  
    
    

    关于wp_list_categories()函数,会专门详细讲解,这里只讲解几个参数
    depth=0&hide_empty=0&title_li=&orderby=id&order=asc&child_of='.$cat_id.''
    表示分类深度depth为0(显示所有分类和子分类),隐藏没有文章的分类hide_empty为0(显示没有文章的分类)。

    文章页获取当前分类目录子目录

    这里需要用到一个自定义函数,即获取文章所属分类目录的父目录。

    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文件里,然后在文章页使用如下代码即可:

    <?php
    $category = get_the_category(); 
    $cat_ID = $category[0]->cat_ID;
    wp_list_categories("child_of=".get_category_root_id($cat_ID). "&depth=0&hide_empty=0&orderby=id&title_li=&order=asc");
    ?>
    

     

    “WordPress获取分类目录下的子目录”共有0条评论

    发表评论

    B em del U Link Code Quote