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

Wordpress侧导航调用当前分类子分类并设置高亮

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

页面顶部一般为主导航,为让主导航简洁,尽量不设计下拉菜单,而把子分类设置在侧面导航。和主导航一样设置高亮,便于用户了解自己所访问的位置。

调用当前分类子分类并设置高亮方法

打开主题目录下的 functions.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_cats('child_of=' . get_category_root_id($cat) . '&depth=1&hide_empty=0&hierarchical=1');?>

其中depth代表分类层级,数字“1”代表着当前栏目的下一级分类(相当于第二级)。当前类目的<li>标签会自动添加类名"current-cat",如下

<ul>
 <li><a href="/list-1//">栏目一</a></li>
 <li class="current-cat"><a href="/list-2/">栏目二</a></li>
</ul>

CSS样式

<style type="text/css">
 ul li.current-cat{color:#fff;background:#c00;}
</style>