获取当前分类下的所有子分类
一般用于taxonomy分类页面,比如产品products,下面有a这个分类,a下面有a-1,a-2,a-3...
如何在进入a分类这个页面的时候,输出这个a下面的子分类?
解决思路:
1.首先通过get_categories
获取所有分类的slug和id
$test = get_categories("taxonomy=product&hide_empty=0");
$cats=array();
foreach($test as $tmpcat){
if($tmpcat->parent==0){
$cats[$tmpcat->term_id]['slug']=$tmpcat->slug;
$cats[$tmpcat->term_id]['term_id']=$tmpcat->term_id;
}
}
3.然后切割分组当前url,判断slug是否等于当前的url
$uri=explode('/',$_SERVER['REQUEST_URI']);
5.等于的话,再根据get_categories
加上child_of=,最后foreach输出所有分类。
foreach($cats as $key=>$val){
if($cats[$key]['slug']==$uri[2]){
$id = $cats[$key]['term_id'];
$cate = get_categories("depth=0&hide_empty=0&title_li=&orderby=ID&order=ASC&taxonomy=product&child_of=$id");
foreach ($cate as $key => $value) {?>
<div class="swiper-slide">
<li class="cat-item<?php if($value->slug == $uri[3]){ echo ' current-cat';}?>"><a href="/products/<?php echo $uri[2];?>/<?php echo $value->slug; ?>/"><?php echo $value->name;?></a></li>
</div>
<?php }
}
}
完整的
<?php
$test = get_categories("taxonomy=product&hide_empty=0");
$cats=array();
foreach($test as $tmpcat){
if($tmpcat->parent==0){
$cats[$tmpcat->term_id]['slug']=$tmpcat->slug;
$cats[$tmpcat->term_id]['term_id']=$tmpcat->term_id;
}
}
foreach($cats as $key=>$val){
if($cats[$key]['slug']==$uri[2]){
$id = $cats[$key]['term_id'];
$cate = get_categories("depth=0&hide_empty=0&title_li=&orderby=ID&order=ASC&taxonomy=product&child_of=$id");
foreach ($cate as $key => $value) {?>
<div class="swiper-slide">
<li class="cat-item<?php if($value->slug == $uri[3]){ echo ' current-cat';}?>"><a href="/products/<?php echo $uri[2];?>/<?php echo $value->slug; ?>/"><?php echo $value->name;?></a></li>
</div>
<?php }
}
}
?>