简体   繁体   English

woocommerce 特色产品类别列表的 wp_query 是否多次显示类别?

[英]wp_query for woocommerce featured product category list is display categories more than once?

I've written a wp_query that checks for featured products in woocommerce.我编写了一个 wp_query 来检查 woocommerce 中的特色产品。

First it gathers all the categories and then it checks if they have featured products.首先它收集所有类别,然后检查它们是否有特色产品。 It then displays the category name.然后显示类别名称。 Only issue I have is it duplicates the cat name for each featured product inside it.我唯一的问题是它重复了其中每个特色产品的猫名。

Any ideas what I've missed that causes the loop to act this way?我错过了什么导致循环以这种方式运行的任何想法? I think my code may be a bit bloated as well.我认为我的代码也可能有点臃肿。

Thank you谢谢

<?php
 $fpArgs = array(
 'post_type' => 'product',
 'tax_query' => array(
    'field'    => 'name',
    'terms'    => 'featured',
    'operator' => 'IN',
 )
);

 $featProds = new WP_Query( $fpArgs );

 if ($featProds->have_posts()):
?>

<section class="standard featuredProducts">

 <?php $cat_terms = get_terms('product_cat'); ?>

 <ul class="nav nav-tabs" id="myTab" role="tablist">

  <?php
    foreach ( $cat_terms as $cat_term ):

      $cat_query = new WP_Query( array(
        'post_type' => 'product',
        'posts_per_page'  => -1,
        'order' => 'ASC',
        'orderby' => 'title',

        'tax_query' => array(
          'relation' => 'AND',
          array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( $cat_term->slug ),
            'operator' => 'IN'
          ),
          array(
              'taxonomy' => 'product_visibility',
              'field'    => 'name',
              'terms'    => 'featured',
              'operator' => 'IN',
          )
        )
      ) );
  ?>

  <?php
    if ( $cat_query->have_posts() ) :
      while ( $cat_query->have_posts() ) :
        $cat_query->the_post();

      $catName = $cat_term->name;
  ?>

  <li class="nav-item" role="presentation">
    <a class="nav-link" id="cat-tab">
      <?php echo $catName; ?>
    </a>
  </li>

  <?php
      endwhile;
     endif;
   endforeach;
  ?>
</ul>

</section>
<?php endif; ?>

I've worked out a solution...我已经想出了一个解决方案...

I added all the categories into an array and used that to select only unique categories with an if statement.我将所有类别添加到一个数组中,并将其用于 select 仅具有 if 语句的唯一类别。

Followed this solution which worked like a charm https://wordpress.stackexchange.com/questions/154970/remove-duplicated-values-from-a-loop遵循这个解决方案,它就像一个魅力https://wordpress.stackexchange.com/questions/154970/remove-duplicated-values-from-a-loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM