Php wp_list_categories()-显示一级类别,仅显示当前术语';子类别页中的子类别
我在用WordPress 具有多个类别及其子类别。在“常规”页面中,我将显示所有一级类别。这是我的密码:Php wp_list_categories()-显示一级类别,仅显示当前术语';子类别页中的子类别,php,wordpress,categories,custom-taxonomy,taxonomy-terms,Php,Wordpress,Categories,Custom Taxonomy,Taxonomy Terms,我在用WordPress 具有多个类别及其子类别。在“常规”页面中,我将显示所有一级类别。这是我的密码: $args = array( 'type' => 'product-items', 'child_of' => 0, 'parent' => '', 'order' => 'DESC', 'hide_empty' => 0, 'hierarchical' => 1, 'exclude' => '',
$args = array(
'type' => 'product-items',
'child_of' => 0,
'parent' => '',
'order' => 'DESC',
'hide_empty' => 0,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'product-category',
'pad_counts' => false,
'depth' => 1,
'title_li' => ''
);
wp_list_categories($args);
单击并进入第一级类别后,只需在其中查看其子类别。当我删除'depth'=>1,
选项时,所有子项都显示在其父类别下,但对于页面速度/加载,在子页面中,我需要显示所有第一级类别,但仅显示当前类别的子项
例如,我有以下3个类别:
- 第一类
- 第2类
- 第3类
- 第一类
- 1的第1子类
- 第2子类别1
- 第3子类别1
- 第2类
- 第1子类,共2个
- 第二类第1子类
- 第二类分包的第二分包
- 第二类分包的第三分包
- 第2子类,共2个
- 第3子类别2
- 第1子类,共2个
- 第3类
- 第1子类,共3个
- 第二小类,共3个
- 第3子类别,共3个
- 第一类
- 1的第1子类
- 第2子类别1
- 第3子类别1
- 第2类
- 第3类
不确定如何使用
wp\u list\u categories()
函数实现这一点。有什么想法吗?我会选择get\u terms()
路径。
例如
$terms = get_terms($args);
foreach($terms as $term){
// If $term is current term use get_terms() again to fetch its children
}
如果使用2个get\u terms()而不是wp\u list\u类别,效果会更好。这将是更快和可定制的。一个用于父类别,另一个用于当前类别的子类别。下面是一个工作示例:
function display_cats($cats,$current=0,$current_children=array()){
$ret= '<ul>';
foreach ($cats as $cs){
$children=($current!=$cs->term_id)?'':display_cats($current_children);
$ret.= '<li> <a href="'.get_term_link($cs->term_id).'"> '.$cs->name.'</a> '.$children.' </li>
';
}
$ret.= '</ul>';
return $ret;
}
$current_cat=9;//for example
$parents=get_terms('product_cat',array('taxonomy'=>'product_cat','echo'=>false,'depth'=>0));
$current_children=get_terms('product_cat',array('taxonomy'=>'product_cat','child_of'=> $current_cat ,'echo'=>false));
echo display_cats($parents,$current_cat,$current_children);
函数显示\u cats($cats,$current=0,$current\u childrent=array()){
$ret=“”;
foreach(猫作为$cs){
$children=($current!=$cs->term\u id)?“”:显示猫($current\u children);
$ret.=“- ”.$children
';
}
$ret.='
';
返回$ret;
}
$current_cat=9//例如
$parents=get_terms('product_cat',array('taxonomy'=>'product_cat','echo'=>false,'depth'=>0));
$current_children=get_terms('product_cat',array('taxonomy'=>'product_cat','child_of'=>$current_cat,'echo'=>false));
回声显示猫($parents,$current,$current,$children,$current,$children);
对于仍然需要帮助的人,这里有一些方法
$category = get_queried_object();
$category_id = $category->term_id;
由此我们将获得当前类别id,并需要将其传递给数组
'child_of' => $category_id,
这将获得当前类别的所有子类别
希望这是有帮助的