如何通过WordPress functions.php在WooCommerce售价元素内添加指定类<div>
解决WooCommerce促销价内添加自定义Div的问题
需求说明
需要在WooCommerce促销价的<span class="woocommerce-Price-amount amount">标签内部,<bdi>标签之前插入一个带类名的Div,用于美化促销价样式。
当前代码结构
<ins> <span class="woocommerce-Price-amount amount"> <bdi> <span class="woocommerce-Price-currencySymbol">$</span>200.00 </bdi> </span> </ins>
期望实现的代码结构
<ins> <span class="woocommerce-Price-amount amount"> <div class="vh-badge-ears"></div> <bdi> <span class="woocommerce-Price-currencySymbol">$</span>200.00 </bdi> </span> </ins>
用户尝试的代码(未达到预期)
function bd_sale_price_html( $price, $product ) { if ( $product->is_on_sale() ) : $return_string = str_replace( '<ins><span class="woocommerce-Price-amount amount">', '<ins><span class="woocommerce-Price-amount amount"><div class="vh-badge-ears"></div>', $price); return $return_string; else : return $price; endif; } add_filter( 'woocommerce_get_price_html', 'bd_sale_price_html', 100, 2 );
问题原因
原代码使用str_replace进行严格字符串匹配,但WooCommerce输出的HTML可能包含空格、换行或属性顺序变化,导致匹配失败,无法插入目标Div。
解决方案
改用正则表达式进行灵活匹配,确保能精准定位目标标签并插入内容。
方案一:匹配所有目标span标签
function bd_sale_price_html( $price, $product ) { if ( $product->is_on_sale() ) { // 正则匹配目标span标签,忽略大小写和前后空白 $price = preg_replace( '/(<span class="woocommerce-Price-amount amount">)/i', '$1<div class="vh-badge-ears"></div>', $price ); } return $price; } add_filter( 'woocommerce_get_price_html', 'bd_sale_price_html', 100, 2 );
方案二:仅匹配<ins>内的目标span标签(更精准)
如果需要避免影响非促销价的相同标签,可以使用更精准的正则:
function bd_sale_price_html( $price, $product ) { if ( $product->is_on_sale() ) { // 仅匹配ins标签内的目标span,兼容标签内的空白和属性 $price = preg_replace( '/(<ins[^>]*>\s*<span class="woocommerce-Price-amount amount">)/i', '$1<div class="vh-badge-ears"></div>', $price ); } return $price; } add_filter( 'woocommerce_get_price_html', 'bd_sale_price_html', 100, 2 );
代码说明
- 使用
preg_replace替代str_replace,正则表达式可忽略HTML中的空白字符和大小写变化,避免匹配失败 $1代表正则匹配到的原标签内容,确保自定义Div插入到目标位置- 保持优先级
100,确保在其他价格HTML处理逻辑之后执行
内容的提问来源于stack exchange,提问作者Massihh
相关产品推荐
相关产品推荐

