【发布时间】:2021-02-23 14:44:41
【问题描述】:
我知道这个问题与之前的问题非常相似,但是提供的答案似乎都不适合我。
但我的问题是,如何按父类别划分子类别?
例如,如果我单击此网站上的气球(见第一张图片),它会将我带到一个新页面,其中子类别被划分,子类别的子类别在其下方组织(见图 2 和 3) .
我已经尝试了所有答案,但似乎都不起作用,而且我想保持相同的层次结构,无论深度如何(产品除外)我已经尝试了下面的代码,但似乎没有工作或显示任何变化
$taxonomies = get_terms( array(
'taxonomy' => 'taxonomy_name',
'hide_empty' => false
) );
if ( !empty($taxonomies) ) :
$output = '<select>';
foreach( $taxonomies as $category ) {
if( $category->parent == 0 ) {
$output.= '<optgroup label="'. esc_attr( $category->name ) .'">';
foreach( $taxonomies as $subcategory ) {
if($subcategory->parent == $category->term_id) {
$output.= '<option value="'. esc_attr( $subcategory->term_id ) .'">
'. esc_html( $subcategory->name ) .'</option>';
}
}
$output.='</optgroup>';
}
}
$output.='</select>';
echo $output;
endif;
我还尝试了以下似乎是我需要的,但它只是在我的网站上造成了严重错误
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
if ( $children ) {
foreach( $children as $subcat ) {
echo '<a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . ' - </a>';
$grandchildren = get_terms( $subcat->taxonomy, array(
'parent' => $subcat->term_id,
'hide_empty' => false
) );
foreach ( $grandchildren as $grandchild ) {
echo '<a href="' . esc_url(get_term_link($grandchild, $grandchild->taxonomy)) . '">' . $grandchild->name . ' - </a>';
}
}
}
我现在正在尝试一种不同的方法,这是我目前所拥有的,我也在使用代码 sn-ps 插件(我不知道这是否会有所不同)
//Return the child categories of a parent
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array( 'parent' => $cat_id )
);
//Print
foreach ( $child_categories as $child ) {
// Here I'm showing as a list...
echo '<li>'.$child ->cat_name.'</li>';
}
【问题讨论】:
-
我试过这个,但它似乎不适合我
-
如果你想不管深度,递归将是你的解决方案
标签: php wordpress woocommerce