You need to enable JavaScript to run this app. WordPress+Woocommerce站点用Weglot翻译产品变体描述失效,如何用其Hook解决
优惠活动
大模型
产品
解决方案
定价
更多

WordPress+Woocommerce站点用Weglot翻译产品变体描述失效,如何用其Hook解决

WooCommerce产品变体文本的Weglot翻译实现方案

核心问题逻辑

默认Weglot仅扫描页面DOM中常规标签内的可见文本,不会解析<form>标签上data-product_variations属性嵌套的JSON结构化内容——包括库存提示、变体描述、尺寸/重量说明、变体属性值这类存在属性内的文本,因此无法被自动纳入翻译范围。

具体实现操作

  • 将以下代码添加到站点主题的functions.php文件,或者安装Code Snippets这类代码片段插件后运行:
    add_filter('weglot_get_custom_translations', function($custom_strings) {
        // 仅在变量产品的详情页执行逻辑
        if(!is_product()) return $custom_strings;
        global $product;
        if(!$product instanceof WC_Product_Variable) return $custom_strings;
    
        $variation_list = $product->get_available_variations();
        foreach($variation_list as $variation) {
            // 提取所有需要翻译的文本字段,与页面输出的data属性内容一一对应
            $custom_strings[] = wp_strip_all_tags($variation['availability_html']);
            $custom_strings[] = wp_strip_all_tags($variation['variation_description']);
            $custom_strings[] = $variation['dimensions_html'];
            $custom_strings[] = $variation['weight_html'];
            // 提取变体属性的可选值文本
            foreach($variation['attributes'] as $attr_value) {
                $custom_strings[] = $attr_value;
            }
            // 如有自定义变体字段(如附加图片说明),在此处补充提取对应字段的值即可
        }
    
        // 去重过滤空值,避免重复抓取
        return array_unique(array_filter($custom_strings));
    });
    
  • 代码运行后的操作流程:
    1. 在Weglot后台触发一次产品页的重新抓取,系统会自动识别新增的自定义翻译字符串
    2. 在Weglot的翻译列表中找到对应原文(库存提示、变体描述等内容),填入对应目标语言的翻译内容
    3. 前端无需额外开发逻辑:Weglot的动态文本匹配机制会自动在WooCommerce渲染变体内容时,替换为对应语言的翻译文本

注意事项

  • 传入Weglot的文本必须和前端最终渲染到页面的原文完全匹配(包含标点、空格、特殊字符),否则会出现翻译匹配失效的问题
  • 不要直接修改data-product_variations属性内的JSON结构内容,否则会导致WooCommerce原生的变体交互逻辑失效
  • 部分带HTML格式的文本可以先通过wp_strip_all_tags()提取纯文本,保证和前端渲染后的内容格式对齐,提升翻译匹配准确率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 07:06:03