只做利于SEO的网站,提供网站建设、SEO、网站代运营等服务。服务中心 | 建站流程 | 网站地图

Wordpress调用当前分类的子分类目录

2021-10-15小猴建站 阅读()相关主题:wordpress

网站经常用到多级菜单,一般来说不超过三层,也就是文章内容最多为第三层,更深层次的分类有可能蜘蛛抓取困难,比如

/list-1/ 为第二层
/list-1/1.html 为第三层

不建议设置成如下的

/list-1/1/ 为第三层
/list-1/1/1.html 为第四层

Wordpress分类页调用该分类或指定分类的的链接及其他

找到模板文件夹的“functions.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号
}

模板调用方法

<?php wp_list_cats('child_of=' . get_category_root_id($cat) . '&depth=1&hide_empty=0&hierarchical=1');?>

注意 wp_list_cats() 这个系统函数会自动生成 <li>  标签,写前端代码的时候要注意细节。