如何在WooCommerce分类页面动态展示全部折扣商品
如何在自定义WooCommerce商品分类模板中显示所有折扣商品
要实现商品分类页面只展示折扣商品(即设置了销售价的商品),可以直接修改自定义模板的查询逻辑,替换原有的主循环。以下是修改后的完整代码:
get_header( 'shop' ); do_action( 'woocommerce_before_main_content' ); ?> <header class="woocommerce-products-header"> <?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?> <h1 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h1> <?php endif; ?> <?php do_action( 'woocommerce_archive_description' ); ?> </header> <?php // 获取当前商品分类ID $current_cat_id = get_queried_object_id(); // 构建折扣商品查询参数 $sale_products_args = array( 'post_type' => 'product', 'posts_per_page' => wc_get_default_products_per_row() * wc_get_default_product_rows_per_page(), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $current_cat_id, 'operator' => 'IN' ) ), 'meta_query' => array( array( 'key' => '_sale_price', 'value' => 0, 'compare' => '>', 'type' => 'numeric' ) ), 'post_status' => 'publish' ); $sale_products_query = new WP_Query( $sale_products_args ); if ( $sale_products_query->have_posts() ) { do_action( 'woocommerce_before_shop_loop' ); woocommerce_product_loop_start(); while ( $sale_products_query->have_posts() ) { $sale_products_query->the_post(); do_action( 'woocommerce_shop_loop' ); wc_get_template_part( 'content', 'product' ); } wp_reset_postdata(); // 重置查询,避免后续内容数据混乱 woocommerce_product_loop_end(); do_action( 'woocommerce_after_shop_loop' ); } else { do_action( 'woocommerce_no_products_found' ); } do_action( 'woocommerce_after_main_content' ); do_action( 'woocommerce_sidebar' ); get_footer( 'shop' );
关键修改说明
- 自动获取当前分类ID:用
get_queried_object_id()直接拿到当前页面对应的商品分类ID,无需手动指定分类。 - 精准筛选折扣商品:通过
meta_query参数,只查询_sale_price字段值大于0的商品——WooCommerce中设置了销售价的商品会自动存储该字段。 - 沿用原有布局设置:
posts_per_page使用WooCommerce默认的每行商品数×每页行数,保持和其他商品页面一致的展示布局。 - 重置查询避免冲突:循环结束后调用
wp_reset_postdata(),防止后续的WordPress查询出现数据错乱问题。
内容的提问来源于stack exchange,提问作者Shakil Hossain
相关产品推荐
相关产品推荐

