我试图得到所有有产品的类别,但也得到没有产品的类别。
WordPress版本4.6.1
wp_dropdown_categories(
array(
\'class\' => \'product-category-field\',
\'id\' => \'product-category\',
\'name\' => \'category\',
\'taxonomy\' => \'product_cat\',
\'selected\' => get_query_var(\'product_cat\' ),
\'hierarchical\' => 1,
\'hide_empty\' => 1,
\'value_field\' => \'slug\',
\'show_count\' => 1
)
);
甚至
get_terms
正在显示带有以下代码的空类别。
<?php $terms = get_terms(\'product_cat\', array( \'parent\' => 0 ));
if( $terms ):
$original_query = $wp_query;
foreach ( $terms as $key => $term ):
?>
<li>
<?php echo $term->name; ?>
<ul>
<?php
$child_terms = get_terms(
\'product_cat\',
array(
\'child_of\' => $term->term_id,
\'hide_empty\' => true
)
);
foreach ( $child_terms as $child_term ) {
$re_child_terms = get_terms(
\'product_cat\',
array(
\'child_of\' => $child_term->term_id,
\'hide_empty\' => true
)
);
if ( ! $re_child_terms ){
?>
<li>
<?php echo $child_term->name; ?>
</li>
<?php
}
}
?>
</ul>
</li>
<?php
endforeach;
$wp_query = null;
$wp_query = $original_query;
?>
</ul>
<?php endif; ?>
注意:在这两种情况下,都不希望显示产品为零的类别。
最合适的回答,由SO网友:Prafulla Kumar Sahu 整理而成
wc_product_dropdown_categories()
将代替wp_dropdown_categories()
.
对于get\\u terms部分
通过替换
$re_child_terms = get_terms( \'product_cat\', array( \'child_of\' => $child_term->term_id, \'hide_empty\' => true ) );
if ( ! $re_child_terms ){
使用
$re_child_terms = get_term_children( $child_term->term_id, \'product_cat\' );
if ( $child_term->count > 0 && empty( $re_child_terms ) ){
解决了我的问题。
不确定,但我认为get\\u术语的问题是here
// Make sure we show empty categories that have children.
if ( $hierarchical && $args[\'hide_empty\'] && is_array( $terms ) ) {
foreach ( $terms as $k => $term ) {
if ( ! $term->count ) {
$children = get_term_children( $term->term_id, $term->taxonomy );
if ( is_array( $children ) ) {
foreach ( $children as $child_id ) {
$child = get_term( $child_id, $term->taxonomy );
if ( $child->count ) {
continue 2;
}
}
}
// It really is empty.
unset( $terms[ $k ] );
}
}
}