从 WP_Query 中的当前产品类别术语 Id 获取所有 Woocommerce 产品

cre*_*ght 2 php wordpress product custom-taxonomy woocommerce

我有一个简单的 taxonomy-product_cat.php 页面,我试图在其中仅显示当前类别中的产品。现在,它正在显示所有产品,而不仅仅是当前类别中的产品。这是我的代码:

<ul class="products">

    <?php
       $current_cat_id = $wp_query->get_queried_object()->term_id;
       $args = array(
         'taxonomy'       => 'product_cat',
         'post_type'      => 'product',
         'post_status'    => 'publish',
         'posts_per_page' => -1,
         'tax_query'      => array(
             'taxonomy'   => 'product_cat',
             'field'      => 'term_id',
             'terms'      => $current_cat_id,
             'operator'   => 'IN'
         )
       );

       $products = new WP_Query( $args );

       while ( $products->have_posts() ) : $products->the_post();
           echo '<li><a href="'. get_permalink() .'"><div class="product__preview"><img src="' . get_the_post_thumbnail_url() . '"></div><span>' . get_the_title() . '</span></a></li>';
       endwhile;

       wp_reset_query();
       ?>
</ul>
Run Code Online (Sandbox Code Playgroud)

我的客户不断更改类别的名称/slug,因此我需要按类别 ID 获取产品。知道为什么这会生成所有产品,而不仅仅是当前类别中的产品吗?

Loi*_*tec 6

更新 2

税务查询需要有 2 个相互嵌入的数组: 'tax_query' => array( array(

删除了第一个不需要的 'taxonomy' => 'product_cat',

替换'terms' => $current_cat_id,'terms' => array( get_queried_object()->term_id ),

替换 wp_reset_query(); 经过wp_reset_postdata();

您的代码将是:

$query = new WP_Query( array(
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'tax_query'      => array( array(
        'taxonomy'   => 'product_cat',
        'field'      => 'term_id',
        'terms'      => array( get_queried_object()->term_id ),
    ) )
) );

while ( $query->have_posts() ) : $query->the_post();
    echo '<li><a href="'. get_permalink() .'"><div class="product__preview"><img src="' . get_the_post_thumbnail_url() . '"></div><span>' . get_the_title() . '</span></a></li>';
endwhile;

wp_reset_postdata();
Run Code Online (Sandbox Code Playgroud)

测试和工作