我有一些代码可以在屏幕上显示子类别,但有些父类别没有子类别,如果是这种情况,我不希望显示该部分。有人知道怎么做吗?以下是我当前显示类别的代码:
<div class="list-group products box">
<h4>Product Range</h4>
<?php $terms = get_the_terms( $post->ID, \'product_cat\' );
foreach ( $terms as $term ){
$category_name = $term->name;
$parent_category_id = $term->term_id;
$categories=get_categories(array( \'parent\' => $category_id ));
$children = get_terms( \'product_cat\', array(
\'parent\' => $parent_category_id,
\'hide_empty\' => true
) );
foreach( $children as $subcat ){
?>
<a href="<?php echo get_term_link( $subcat->slug, \'product_cat\' ); ?>" class="list-group-item"><?php echo $subcat->name; ?></a>
<?php } } ?>
</div>
当父母没有孩子时,它只显示H4产品系列
最合适的回答,由SO网友:Krishna Joshi 整理而成
尝试以下代码
<?php
$terms = get_the_terms($post->ID, \'product_cat\');
foreach ($terms as $term) {
$category_name = $term->name;
$parent_category_id = $term->term_id;
$categories = get_categories(array(\'parent\' => $category_id));
$children = get_terms(\'product_cat\', array(
\'parent\' => $parent_category_id,
\'hide_empty\' => true
));
if (!empty($children)) {
echo \' <div class="list-group products box">
<h4>Product Range</h4>\';
foreach ($children as $subcat) {
?>
<a href="<?php echo get_term_link($subcat->slug, \'product_cat\'); ?>" class="list-group-item"><?php echo $subcat->name; ?></a>
<?php
}
echo "</div>";
}
}
?>
希望这有帮助