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

如何修改WooCommerce Subscriptions的价格字符串文本

你的代码分析与完善方案

你的核心思路是完全正确的,但存在一个明显的语法错误需要修正,另外还有几个细节可以优化,让功能更健壮:

1. 首先修正语法错误

你在add_filter调用里的函数名没写完(wc_subscriptions_custom_price_str...),这会导致代码完全不生效。把它改成完整的函数名wc_subscriptions_custom_price_string即可解决这个问题。

2. 修正后的基础可用代码

// WC Subscriptions - Custom Price String
function wc_subscriptions_custom_price_string( $pricestring ) {
    // 替换"sign-up fee"为"down payment"
    $pricestring = str_replace( 'sign-up fee', 'down payment', $pricestring );
    // 移除"with 1 month free trial"文本
    $pricestring = str_replace( 'with 1 month free trial', '', $pricestring );
    // 可选:清理替换后可能产生的多余空格
    $pricestring = preg_replace( '/\s+/', ' ', trim( $pricestring ) );
    return $pricestring;
}
add_filter( 'woocommerce_subscriptions_product_price_string', 'wc_subscriptions_custom_price_string' );

3. 进阶优化建议

  • 适配多语言站点:如果你的站点支持多语言,直接用str_replace替换硬编码的英文文本可能会失效(因为翻译后的字符串会变化)。这种情况下,建议针对WooCommerce的翻译钩子修改,直接干预翻译后的文本:
function wc_subscriptions_translate_custom_strings( $translated_text, $text, $domain ) {
    if ( 'woocommerce-subscriptions' === $domain ) {
        switch ( $translated_text ) {
            case 'sign-up fee':
                $translated_text = 'down payment';
                break;
            case 'with 1 month free trial':
                $translated_text = '';
                break;
        }
    }
    return $translated_text;
}
add_filter( 'gettext', 'wc_subscriptions_translate_custom_strings', 20, 3 );

这个方法更适配多语言场景,因为它直接修改插件翻译后的文本内容。

  • 精准避免误替换:如果担心有相似文本被误替换,可以用正则表达式匹配完整短语边界:
$pricestring = preg_replace( '/\bsign-up fee\b/', 'down payment', $pricestring );

\b代表单词边界,确保只替换独立的"sign-up fee"短语,而不是包含它的更长字符串。

  • 保留HTML格式:如果价格字符串包含HTML标签(比如<span>),直接替换文本可能破坏格式。这种情况可以用DOM解析来修改文本内容,但对于大多数普通场景,基础的字符串替换已经足够。

总的来说,你的核心逻辑没问题,修正语法错误后就能正常工作,进阶优化可以根据你的站点实际需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:56