我只想将测试标签添加到具有子类别的类别。当我尝试运行此代码时,测试标签会显示在每个类别中。我为此代码使用Woocommerce。谢谢
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<li>';
echo '<a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
if($cat->category_parent == 0) {
echo 'test';
}
echo '</li>';
}
}
?>
答案 0 :(得分:0)
get_categories
返回WP_Term的数组,其中不包含category_parent
成员。由于null == 0
为null,因此返回true,而您的条件始终为true。将其替换为$cat->parent
。
您还可以在parent
中指定get_categories
参数,并跳过此检查。
$args = array(
...
'parent' => 0, // get only top level categories
...
);