wordpress调用当前分类的子分类,无子分类则显示默认菜单
如何在自己建网站时显示当前分类下的子分类或者在文章页显示所属分类的子分类这样的问题,在使用wordpress建网站时,往往需要在侧边栏调用当前栏目的子分类子目录,而且在点击子目录时,还会侧边栏显示这些子目录的分类。
WordPress在企业网站制作时,需要在网站的边栏列出企业产品分类,如果公司网站产品项目很多的情况,就需要设置二级分类或者子分类。
此方法也适用于文章页面。
1.首先在网站主题的函数模板function.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号
}
2.然后在页面要显示子分类的地方(一般是在侧边栏)粘贴下面这段代码即可
<?php
$root_id = get_category_root_id($cat);
$cats = get_categories(array(
'child_of' => $root_id,
//'parent' => $cat,
'hide_empty' => 0
));
$cat_num = count($cats);
if (is_single()) {
$cat_single = get_the_category();
$parent = $cat_single[0]->category_parent;
$root_id = $parent;
}
//var_dump(get_the_category(),$root_id, $cats);
if ((is_category() && $cat_num > 0) || (is_single() && $parent != 0)) {
?>
<div class="list">
<div class="title">
<h4><?php echo get_cat_name($root_id); ?></h4>
<span class="en">News Center</span>
</div>
<div class="con">
<ul>
<?php wp_list_categories(array(
'orderby' => 'name',
'child_of' => $root_id,
'title_li' => '',
'hide_empty' => 0
)); ?>
</ul>
<div class="clear"></div>
</div>
</div>
<?php } elseif (1 || is_page()) {
?>
<div class="list">
<div class="title">
<h4>关于我们</h4>
<span class="en">News Center</span>
</div>
<div class="con">
<ul>
<?php wp_nav_menu(array('theme_location' => 'leftmenu', 'container' => '<ul>', 'menu_id' => 'menu', 'menu_class' => 'menu', 'link_before' => '<span>', 'link_after' => '</span>',)); ?>
</ul>
<div class="clear"></div>
</div>
</div>
<?php } ?>
说明:如果没有子分类就显示默认的菜单,有子分类则自动显示子分类栏目。
写笔记