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

如何在指定WooCommerce端点上条件替换文本并解决报错问题?

问题根源

gettext 是WordPress触发时机最早的钩子之一,在WooCommerce的页面判断函数(is_wc_endpoint_url、is_account_page)还没完成加载初始化的时候就会执行,直接在回调里调用这些未定义的函数就会触发站点报错。


可行解决方案

把gettext过滤器的注册延迟到WooCommerce函数加载完成之后再执行,同时增加函数存在判断做兼容:

// 等到init钩子触发(此时WooCommerce函数已加载完成)再注册文本替换过滤器
add_action('init', 'register_custom_endpoint_text_replace');
function register_custom_endpoint_text_replace() {
    // 仅在前台页面加载过滤器,避免后台执行产生额外性能消耗
    if (!is_admin()) {
        add_filter('gettext', 'change_endpoint_text');
    }
}

function change_endpoint_text( $translated ) {
    // 先判断WooCommerce端点判断函数存在,再执行页面条件判断
    if (function_exists('is_wc_endpoint_url') && is_wc_endpoint_url('wc-smart-coupons')) {
        $translated = str_ireplace( 'List of coupons which are valid & available for use. Click on the coupon to use it. The coupon discount will be visible only when at least one product is present in the cart.', 'List of vouchers which are valid & available for use. Click on a voucher to use it. The discount will be visible only when at least one product is present in the cart.', $translated );
    }
    return $translated;
}

如果需要判断「我的账户」全页面,把条件替换为function_exists('is_account_page') && is_account_page()即可正常生效。


优化版本(性能更高)

利用gettext钩子的完整参数精准匹配文本,避免全局扫描所有字符串产生额外消耗:

add_action('init', 'register_custom_endpoint_text_replace');
function register_custom_endpoint_text_replace() {
    if (!is_admin()) {
        // 声明接收gettext的3个参数,优先级10,参数数量3
        add_filter('gettext', 'change_endpoint_text', 10, 3);
    }
}

function change_endpoint_text( $translated, $original_text, $domain ) {
    if (function_exists('is_wc_endpoint_url') && is_wc_endpoint_url('wc-smart-coupons')) {
        // 直接匹配原始文本,不会误替换其他位置的相似内容
        if ($original_text == 'List of coupons which are valid & available for use. Click on the coupon to use it. The coupon discount will be visible only when at least one product is present in the cart.') {
            $translated = 'List of vouchers which are valid & available for use. Click on a voucher to use it. The discount will be visible only when at least one product is present in the cart.';
        }
    }
    return $translated;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:18:05