【www.xieat.com - 科技】
由于本博基本上都存在二级分类,所以有必要在wordpress在一级分类的页面里显示该分类下的二级分类,比如以下几个分类:
世界之最》生物界之最
世界之最》人类之最
世界之最》自然界之最
必须在博友们点开世界之最分类的时候,页面右侧的导航变成生物界之最,人类之最,自然界之最
在网上找了很多代码,终于找到如下一段比较合适使用。
global $cat;
$cats = get_categories(array(
"child_of" => $cat,
"parent" => $cat,
"hide_empty" => 0
));
$c = get_category($cat);
if(empty($cats)){
?>
" href="">
">全文阅读>>
| 标签:
文章稍后更新
}else{
foreach($cats as $the_cat){
$posts = get_posts(array(
"category" => $the_cat->cat_ID,
"numberposts" => 10,
));
if(!empty($posts)){
echo "
name."" href="".get_category_link($the_cat)."">".$the_cat->name."
- ";
foreach($posts as $post){
echo "".mysql2date("Y-m-d", $post->post_date)."
post_title."" href="".get_permalink($post->ID)."">".$post->post_title."";
}
echo "
";
}
}
}
?>
但是这种方法也有问题,放在右侧时会让中间显示的博文列表出现错误,大家在使用时就会发现了,所以不适合我的这种需求,但是可以用来做生成二级分类的文章列表之用。后来又找到如下方法:
在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
};
然后在需要调用 二级分类的地方使用:
if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" )
{
echo wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC");
}
?>
这样就可以了,
只有要分类页面才显示二级分类,其它页则显示左侧小工具,记录于此,以防忘记,效果就如本博左侧显示的那样。
本文来源:http://www.xieat.com/keji/27811/
推荐访问:wordpress二级菜单