【问题标题】:Return results in foreach only when category has products WooCommerce仅当类别具有产品 WooCommerce 时才在 foreach 中返回结果
【发布时间】:2020-08-11 15:34:16
【问题描述】:

我需要下面的 foreach 仅在类别有产品链接到它时才返回结果。目前它还返回 Woocommerce 的“未分类类别”,我需要过滤掉该类别或任何没有产品的类别。这可能是一个快速修复,但我无法弄清楚。

<?php

defined( 'ABSPATH' ) || exit;

function wcc_product_by_cat() {

  $args = array(
      'number'     => $number,
      'orderby'    => 'title',
      'order'      => 'ASC',
      'hide_empty' => $hide_empty,
      'include'    => $ids
  );
  $product_categories = get_terms( 'product_cat', $args );
  $count = count($product_categories);
  if ( $count > 0 ){
      echo '<div id="cat-list__sidebar">';
      foreach ( $product_categories as $product_category ) {
          echo '<div class="card"><div class="card-header" id="heading-'. $product_category->slug .'"><h5 class="mb-0"><button class="btn btn-link" data-toggle="collapse" data-target="#'. $product_category->slug .'" aria-expanded="true" aria-controls="'. $product_category->slug .'">' . $product_category->name . '</button></h5></div>';
          $args = array(
              'posts_per_page' => -1,
              'orderby'    => 'title',
              'order'      => 'ASC',
              'tax_query' => array(
                  'relation' => 'AND',
                  array(
                      'taxonomy' => 'product_cat',
                      'field' => 'slug',
                      'terms' => $product_category->slug
                  )
              ),
              'post_type' => 'product',
              'orderby' => 'title,'
          );
          $products = new WP_Query( $args );
          echo '<div id="'. $product_category->slug .'" class="collapse" aria-labelledby="heading-'. $product_category->slug .'" data-parent="#cat-list__sidebar"><div class="card-body"><ul>';
          while ( $products->have_posts() ) {
              $products->the_post();
              ?>
                  <li>
                      <a href="<?php the_permalink(); ?>">
                          <?php the_title(); ?>
                      </a>
                  </li>
              <?php
          }
          echo '</ul></div></div></div>';
      }
      echo '</div>';
  }

}

add_action(
  'wcc_before_shop_sidebar',
  'wcc_product_by_cat', 10);

?>

【问题讨论】:

    标签: php wordpress if-statement woocommerce foreach


    【解决方案1】:
    $args = array(
              'number'     => $number,
              'orderby'    => 'title',
              'order'      => 'ASC',
              'hide_empty' => true, // This will hide category without products
              'include'    => $ids
          );
    
    $product_categories = get_terms( 'product_cat', $args );
    

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2017-01-31
      相关资源
      最近更新 更多