本文最后更新于 1315 天前,其中的信息可能已经有所发展或是发生改变。
wordpress的导航栏目高亮有两种情况分别是页面page和分类category,高亮方法是通过判断当前页面是page还是category,再获取其父id。如果已经是最顶级id,则使用顶级id。最后通过获取的id使用js来对其标签新增类,来实现导航高亮
html
对于html只需要在要高亮的标签中添加nav+id这样一个类,如:<li id="nav8">
function
在functions.php中添加函数
//获取页面id,给导航高亮
function get_id(){
global $post,$getpage_id;
$postid = get_the_ID();//id
$parent_id = $post -> post_parent;//父id
return $getpage_id = $parent_id == 0 ? $postid : $parent_id;
}
//获取分类id
function get_cid($cat){
$c = get_category($cat);
while($c -> category_parent){
$c = get_category($c -> category_parent);
}
$c = $c -> term_id;
$cat = $c ==0 ? $cat : $c;
return $cat;
}
js
js中调用php函数获取当前页面的顶级id值
<script type="text/javascript">var navID = "<?php if(is_category()){echo get_cid($cat);}else{echo get_id();}?>";</script>
最后添加高亮的类名
$("#nav" + navID).addClass("on");








