You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce加购按钮返回文本中添加带price类的span标签

问题原因

你之前的写法达不到预期有两个核心原因:

  • woocommerce_product_add_to_cart_text 钩子的返回值默认会被WooCommerce做HTML转义处理,你写的标签会被转成字符实体,直接显示为纯文本而不会被识别为HTML标签
  • 你保留了原代码的strip_tags()函数,这个函数会清除所有HTML标签,就算不转义你加的span也会被删掉,同时你写的<本身就是转义后的左尖括号实体,本来就不会被识别为标签开头

解决方法

你需要调整原函数的返回逻辑,同时新增一行过滤器关闭加购按钮文本的HTML转义,完整修改后的代码如下:

// 关闭加购按钮文本的HTML转义,允许输出span标签
add_filter( 'woocommerce_esc_html_add_to_cart_text', '__return_false' );

add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // 店铺/归档页
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // 商品详情页
function custom_add_to_cart_price( $button_text, $product ) {
    // 可变商品
    if( $product->is_type('variable') ) {
        // 店铺/归档页
        if( ! is_product() ){
            $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
            $clean_price = strip_tags( $product_price );
            // 插入带price类的span标签
            return $button_text . ' - From <span class="price">' . $clean_price . '</span>';
        } 
        // 商品详情页
        else {
            return $button_text;
        }
    } 
    // 其他所有商品类型
    else {
        $product_price = wc_price( wc_get_price_to_display( $product ) );
        $clean_price = strip_tags( $product_price );
        // 插入带price类的span标签
        return $button_text . ' - <span class="price">' . $clean_price . '</span>';
    }
}

注意事项

  • Google Merchant抓取规则要求价格类的class建议使用小写price,和代码里的写法一致即可被正常识别
  • 如果你使用的WooCommerce版本低于6.0,没有woocommerce_esc_html_add_to_cart_text过滤器,可以替换为直接修改加购按钮完整HTML的方式实现,调整对应钩子逻辑即可

内容的提问来源于stack exchange,提问作者Connor Alaves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:45:02