我有这种情况,我想弄明白 .

我创建了一个名为cities的自定义产品分类,每个产品都属于 product_cat 分类和/或 city 分类 .

在商店产品类别中,我想创建一个小部件,显示当前类别的可用城市 .

我设法做到了这一点,但它不是我正在寻找的优化代码 .

现在这就是它的样子

// get current category
$cate = get_queried_object();
         $catID = $cate->term_id;
         $catID;
          $link = get_term_link( $catID, 'product_cat' );

         $args = array(
          'post_type' => 'product',
          'tax_query' => array(
            'taxonomy' => 'product_cat',
            'field'    => 'id',
            'term'     =>  $catID
            )
          );

         $products = new WP_Query( $args );

         $cities = array();

         foreach ($products->posts as $product) {
          echo('<ul>');
           $terms = get_the_terms($product->ID,'city');
           if (is_array($terms)) {
            foreach ($terms as $term) {
              if (!in_array($term->slug, $cities)) {
                $cities[] = $term->slug;
                $city_link = get_term_link( $term->term_id, 'city' );
                echo "<li><a href='{$link}city/{$term->slug}'>{$term->name}</a></li>";
              }
            }
          }
          echo('</ul>');
        }

如果不是WP_Query函数,我认为它可以通过SQL查询来完成,但这不属于我的联盟 .