如何用Elementor在WooCommerce单个产品页面显示促销标签?
在Elementor中为WooCommerce单个产品页添加促销标签的方法
Elementor默认的单个产品页模块确实没有内置促销标签的显示选项,但可以通过短代码或动态标签来实现,以下是具体方案:
方案一:自定义短代码实现
- 将以下代码添加到主题的
functions.php文件,或使用自定义代码插件(如Code Snippets)插入:
function display_woocommerce_sale_badge() { global $product; if ( ! is_a( $product, 'WC_Product' ) ) return ''; if ( $product->is_on_sale() ) { // 处理简单/外部产品 if ( in_array( $product->get_type(), ['simple', 'external'] ) ) { $regular_price = $product->get_regular_price(); $sale_price = $product->get_sale_price(); if ( $regular_price && $sale_price ) { $discount = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 ); return '<span class="onsale">-'.$discount.'%</span>'; } } // 处理可变产品 elseif ( $product->get_type() === 'variable' ) { $discounts = []; foreach ( $product->get_available_variations() as $variation ) { $reg_price = $variation['display_regular_price']; $sale_price = $variation['display_price']; if ( $reg_price > $sale_price ) { $discounts[] = round( ( ( $reg_price - $sale_price ) / $reg_price ) * 100 ); } } if ( ! empty( $discounts ) ) { return '<span class="onsale">-'.max( $discounts ).'%</span>'; } } // 默认促销标签 return '<span class="onsale">促销</span>'; } return ''; } add_shortcode( 'woocommerce_sale_badge', 'display_woocommerce_sale_badge' );
- 回到Elementor单个产品页编辑器,添加「短代码」模块,输入
[woocommerce_sale_badge]即可调用促销标签。 - 可通过自定义CSS调整标签样式,比如在Elementor的「自定义CSS」面板添加:
.onsale { background: #ff4444; color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; position: absolute; top: 10px; right: 10px; }
方案二:Elementor动态标签(无代码方案)
如果不想写代码,可通过动态标签实现基础的促销提示:
- 在单个产品页编辑器中添加「文本」或「HTML」模块
- 点击模块内的动态标签按钮(⚡图标),选择「自定义字段」,再选择
wc_product_is_on_sale - 设置显示规则:当字段值为
true时,显示自定义文本(如「促销」) - 若要显示折扣百分比,需结合价格动态标签手动计算,或使用Elementor Pro的动态条件功能优化显示逻辑
补充说明
产品归档页能显示促销标签,是因为WooCommerce默认归档模板已包含该渲染逻辑,而Elementor单个产品页模块未内置此功能,因此需要手动添加。
内容的提问来源于stack exchange,提问作者Arpan Jain
相关产品推荐
相关产品推荐

