WooCommerce 6:折扣百分比前置显示或On-sale badge排版调整求助
解决WooCommerce产品折扣百分比显示及在售徽章同行问题
方案1:重写函数在价格前显示折扣百分比(支持简单/可变产品)
旧代码存在可变产品折扣计算逻辑错误(错误重置了$percentage变量),导致无法正确计算折扣率,且折扣位置不符合需求。以下是修复并优化后的代码:
add_filter( 'woocommerce_get_price_html', 'custom_price_with_discount_percent', 100, 2 ); function custom_price_with_discount_percent( $price, $product ) { if ( is_admin() ) return $price; $discount_html = ''; $max_discount = 0; // 处理简单产品 if ( $product->is_type('simple') && $product->is_on_sale() ) { $regular_price = (float) $product->get_regular_price(); $sale_price = (float) $product->get_sale_price(); if ( $regular_price > 0 && $sale_price > 0 ) { $max_discount = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 ); } } // 处理可变产品 elseif ( $product->is_type('variable') && $product->is_on_sale() ) { foreach ( $product->get_visible_children() as $variation_id ) { $variation = wc_get_product( $variation_id ); if ( !$variation->is_on_sale() ) continue; $reg_price = (float) $variation->get_regular_price(); $sale_price_var = (float) $variation->get_sale_price(); if ( $reg_price > 0 && $sale_price_var > 0 ) { $discount = round( ( ( $reg_price - $sale_price_var ) / $reg_price ) * 100 ); if ( $discount > $max_discount ) { $max_discount = $discount; } } } } // 生成折扣百分比HTML,放在价格前 if ( $max_discount > 0 ) { $discount_html = '<span class="discount-percent">-'.$max_discount.'%</span> '; } // 保留原需求的M.R.P.和Price前缀修改 if ( $product->is_on_sale() ) { $price = str_replace( '<del>', '<del>M.R.P.: ', $price ); $price = str_replace( '<ins>', '<ins>Price: ', $price ); } return $discount_html . $price; }
添加以下CSS样式优化显示效果:
.discount-percent { color: #e74c3c; font-weight: bold; margin-right: 8px; }
该函数会自动识别简单/可变产品,计算最大折扣百分比并显示在价格前方,同时保留原有的价格前缀修改逻辑。
方案2:将On-sale徽章与产品价格置于同一行
若无需修改代码,仅通过CSS调整布局,可添加以下样式:
/* 产品列表页样式 */ .woocommerce ul.products li.product .onsale { position: static; display: inline-block; margin-right: 10px; vertical-align: middle; } .woocommerce ul.products li.product .price { display: inline-block; vertical-align: middle; } /* 单个产品页样式(按需添加) */ .woocommerce div.product p.price .onsale { position: static; display: inline-block; margin-right: 10px; vertical-align: middle; }
通过将默认绝对定位的在售徽章改为inline-block,使其与价格容器处于同一行并垂直对齐。
内容的提问来源于stack exchange,提问作者Volodymyr Tymko
相关产品推荐
相关产品推荐

