PHP中如何让后台动态文本字段支持WPML多语言翻译识别?
动态优惠字段适配WPML翻译解决方案
核心思路是将后台自定义存储的动态文本注册到WPML字符串翻译表,调用时走WPML翻译接口拉取对应语言结果,即可保证每个活动的自定义文本都能被正确识别翻译。
具体实现步骤
步骤1:后台保存优惠规则时注册动态字符串
在后台保存text_in_modal_special_offer字段的逻辑中新增注册代码,将每个活动的自定义文本独立注册到WPML:// 保存优惠规则时同步注册翻译字符串 if (isset($_POST['text_in_modal_special_offer'])) { $custom_text = sanitize_text_field($_POST['text_in_modal_special_offer']); // 参数依次为:文本域、字符串唯一标识、原始字符串 icl_register_string('discountText', 'offer_rule_text_' . $rule['key'], $custom_text); }用规则ID作为标识后缀,避免不同活动的字符串冲突
步骤2:修改前端读取逻辑,调用翻译接口
将原有代码替换为如下版本,优先调用已注册自定义文本的翻译结果,无自定义文本时走默认翻译:if ( $total_to_add - $total_added > 0 ) { if ( ! in_array( $rule['key'], $special_offers, true ) ) { if (isset( $rule['text_in_modal_special_offer'] )) { // 调用WPML翻译接口拉取对应语言的自定义文本 $rule_text = icl_t('discountText', 'offer_rule_text_' . $rule['key'], $rule['text_in_modal_special_offer']); } else { $rule_text = __( 'Get a special discount if you add {{total_to_add}} product(s) to your order.', 'discountText' ); } $special_offer = array( 'text' => $rule_text, 'items_in_cart' => $total_added, 'discount' => array( 'type' => $discount['discount_amount']['type'], 'amount' => $discount['discount_amount']['amount'], ), ); $special_offers[ $rule['key'] ] = $special_offer; } }
效果验证
完成配置后新建优惠活动并保存自定义文本,进入WPML后台「字符串翻译」页面,筛选discountText文本域即可看到对应动态文本,翻译后即可在前端对应语言版本生效。
内容的提问来源于stack exchange,提问作者Bassam Radi
相关产品推荐
相关产品推荐

