![](/img/trans.png)
[英]Get Woocommerce products by custom taxonomy term values in a WP_Query
[英]Get all Woocommerce products from current product category term Id in a WP_Query
我有一个简单的 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
税务查询需要有 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();
测试和工作
虽然它的正确答案你可以通过类别slug得到它。
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'product_cat' => 'category slug here',
);
$products_all = new WP_Query( $args );
测试版本 4.6.1
$terms = wp_get_post_terms( $product->id, 'product_cat' );
$args_listing = array(
'post_type' => 'product',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $terms[0]->term_id,
) ),
'orderby'=> 'date',
'order'=> "desc",
'posts_per_page' => 10,
'paged' => $paged
);
I think you can try this. its working for me.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.