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

通过functions.php修改WordPress+ACF repeater字段文本遇致命错误求助

ACF Repeater字段实现内容替换的致命错误排查与修复

问题场景

通过functions.php借助ACF选项页(translation_slow)的repeater字段实现网站内容替换,改写原静态数组替换的gettext过滤器函数后出现致命错误/白屏。

原参考函数:

function multi_change_translate_text( $translated ) {
    $text       = array(
        'Old Text 1' => 'New Text 1',
    );
    $translated = str_ireplace( array_keys( $text ), $text, $translated );
    return $translated;
}
add_filter( 'gettext', 'multi_change_translate_text', 20 );

改写后的出错代码:

// Translate Strings

function multi_change_translate_text( $translated ) {
    $text = array();

    $repeater_values = get_field('tlumaczenie_slow', 'option');

    foreach($repeater_values as $value) {

        $old_text = $value['old_text'];
        $new_text = $value['new_text'];

        $text[$old_text] = $new_text;
    }

    $translated = str_ireplace( array_keys( $text ), $text, $translated );
    return $translated;
}
add_filter( 'gettext', 'multi_change_translate_text', 20 );

错误原因

  1. ACF函数未初始化:get_field函数在gettext钩子触发时可能还未加载,直接调用会抛出「函数未定义」的致命错误。
  2. Repeater字段值无效:当ACF选项页中没有添加任何替换条目时,get_field返回false而非数组,直接执行foreach会抛出「Invalid argument supplied for foreach()」错误。
  3. 钩子参数不完整:gettext过滤器原生包含3个参数($translated, $text, $domain),仅声明1个参数虽不直接报错,但不符合规范且可能影响后续逻辑扩展。

修复后的代码

// Translate Strings
function multi_change_translate_text( $translated, $text, $domain ) {
    // 确保ACF函数已加载,避免函数未定义错误
    if ( ! function_exists( 'get_field' ) ) {
        return $translated;
    }

    $text_replacements = array();
    $repeater_values = get_field('tlumaczenie_slow', 'option');

    // 验证repeater返回值为有效数组后再遍历
    if ( is_array( $repeater_values ) ) {
        foreach( $repeater_values as $value ) {
            // 确保子字段存在且旧文本不为空,避免无效替换
            if ( isset( $value['old_text'], $value['new_text'] ) && ! empty( $value['old_text'] ) ) {
                $text_replacements[ $value['old_text'] ] = $value['new_text'];
            }
        }
    }

    // 仅当存在有效替换规则时执行替换
    if ( ! empty( $text_replacements ) ) {
        $translated = str_ireplace( array_keys( $text_replacements ), $text_replacements, $translated );
    }

    return $translated;
}
// 声明过滤器的3个参数,优先级保持20
add_filter( 'gettext', 'multi_change_translate_text', 20, 3 );

关键修复点

  • 增加function_exists('get_field')判断,避免ACF未加载时的致命错误。
  • 用is_array()验证repeater字段返回值,防止遍历非数组数据报错。
  • 增加子字段存在性与非空判断,过滤无效的替换条目。
  • 完整声明gettext过滤器的3个参数,符合WordPress钩子规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:20:38