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

时间:2018-09-11 16:24:17

标签: php wordpress woocommerce product custom-taxonomy

我有一个简单的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>

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

2 个答案:

答案 0 :(得分:3)

更新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();

经测试可正常工作

答案 1 :(得分:0)

尽管答案正确,但您可以通过类别“ slug”来获得它。

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'category slug here',
    );
    $products_all = new WP_Query( $args );

版本测试为4.6.1

相关问题