0

我只想将测试标签添加到具有子类别的类别。当我尝试运行此代码时,每个类别都会显示测试标签。我正在为这段代码使用 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>';
    }      
}

?>
4

1 回答 1

0

get_categories返回不包含成员的WP_Term数组。category_parent因为它为 null,所以null == 0返回 true,并且您的条件始终为 true。将其替换为$cat->parent

您也可以在 中指定parent参数get_categories,并跳过此检查。

$args = array(
 ...
 'parent' => 0, // get only top level categories
 ...
);
于 2020-07-30T12:14:49.373 回答