Php 从WP_查询中的当前产品类别术语Id获取所有Woocommerce产品
我有一个简单的taxonomy-product_cat.php页面,我试图只显示当前类别中的产品。现在,它显示的是所有产品,而不仅仅是当前类别中的产品。这是我的密码:Php 从WP_查询中的当前产品类别术语Id获取所有Woocommerce产品,php,wordpress,woocommerce,product,custom-taxonomy,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' =&g
<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 税务查询需要有两个相互嵌入的数组:
'tax\u query'=>数组(数组(
删除了第一个不需要的'taxonomy'=>'product\u cat',
将'terms'=>$current\u cat\u id,
替换为'terms'=>数组(get\u queryed\u object()->term\u 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();
$query=新的WP\u查询(数组)(
“post_类型”=>“产品”,
“发布状态”=>“发布”,
“每页帖子数”=>-1,
“tax_query”=>数组(数组(
“分类法”=>“产品分类”,
'field'=>'term_id',
'terms'=>数组(获取\u查询的\u对象()->term\u id),
) )
) );
而($query->have_posts()):$query->the_post();
回音“”;
结束时;
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.1Hmmm,这似乎没有什么区别:(我已经删除了
$wp query->
,以及第一个'taxonomy'=>'product\u cat'
,但我仍然得到了所有的产品。可能是另一个代码片段干扰了其他地方吗?仍然没有运气。\我尝试在'terms'
插槽中编码一个无意义的数字,但它仍然显示所有的产品,所以它似乎没有你根本不需要阅读这些条款。