如何按分类ID显示WooCommerce特色产品?现有代码显示全部特色产品
按分类ID筛选并展示WooCommerce特色产品
要实现按指定分类ID筛选特色产品,只需在原代码的tax_query中添加针对产品分类(product_cat)的筛选条件即可。以下是修改后的完整代码:
<?php // 替换为你需要的分类ID,多个ID可使用数组如 array(12, 15) $category_id = 10; $meta_query = WC()->query->get_meta_query(); $tax_query = WC()->query->get_tax_query(); // 筛选特色产品的条件 $tax_query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'name', 'terms' => 'featured', 'operator' => 'IN', ); // 新增:按分类ID筛选的条件 $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $category_id, 'operator' => 'IN', ); $args = array( 'meta_query' => $meta_query, 'tax_query' => $tax_query, ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); wc_get_template_part( 'content', 'product' ); endwhile; // 重置查询,避免影响后续内容 wp_reset_postdata(); ?>
关键说明:
- 先定义
$category_id变量,填入目标产品分类的ID,支持单个ID或ID数组(用于同时筛选多个分类)。 - 新增的
tax_query条目针对WooCommerce产品分类的product_cattaxonomy,通过term_id匹配分类ID,IN操作符兼容单/多分类场景。 tax_query默认逻辑为AND,因此最终会返回同时满足「属于指定分类」和「是特色产品」的商品。- 最后添加
wp_reset_postdata(),确保当前查询循环不会干扰页面后续的WP查询逻辑。
内容的提问来源于stack exchange,提问作者ahmed hasan
相关产品推荐
相关产品推荐

