
wordpress分类页输出父子分类链接效果
看到知更鸟博客在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);
}
// 返回根分类的id号
return $this_category->term_id;
}//获取子分类的父分类
function get_category_cat() {
$catID = get_query_var('cat'); // 当前分类ID
$thisCat = get_category($catID);
$parentCat = get_category($thisCat->parent);
// 输出父分类的链接
echo '<a href="'.get_category_link($parentCat->term_id).'">'.get_cat_name($parentCat->term_id).'</a>';
}
在需要输出的分类页模板中输出代码
<div class="cotegorylist"><ul><li class="cat-item"><?php echo get_category_cat();?><?php //echo get_category_parents( $cat, true, ' » ' ); ?></li>
<?php wp_list_categories('child_of=' . get_category_root_id($cat) . '&depth=1&hide_empty=0¤t_category=0&$parent_category=1&hierarchical=1&optioncount=1&title_li=');?></ul></div><style>
/*css*/
.cotegorylist ul {
display: flex;
justify-content: center;
flex-wrap: wrap;
margin: 5px 0 7px;
padding: 2px 0 0;
}
.cotegorylist .cat-item {
background: #fff;
width: auto;
font-size: 14px;
font-size: 1.4rem;
color: #444;
text-align: center;
line-height: 180%;
display: inline-block;
cursor: pointer;
margin: 0 4px 8px;
padding: 8px 16px;
border-radius: 5px;
box-shadow: 0 0 0 1px rgb(68 68 68 / 5%);
}</style>