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

如何通过WPML钩子获取WooCommerce全局属性标签翻译

获取WooCommerce全局属性翻译的解决方案

我正尝试获取部分WooCommerce全局属性的翻译内容,目前已掌握这些属性的ID与slug,但尚未找到可行的实现方法。

已尝试使用以下过滤器:

  • wpml_object_id
  • wpml_translate_single_string

但卡在找不到apply_filters函数中正确的$element_type参数,之前的示例代码如下:

apply_filters('wpml_object_id', $attribute->id, $element_type, FALSE, $current_language_code);

WPML wpml_object_id 钩子说明

该钩子用于获取对象在目标语言中的对应ID,参数细节如下:

  1. $object_id:原始属性的ID(必填参数)
  2. $element_type:对于WooCommerce全局属性,正确的类型值有两种:
    • 格式为 'pa_' + 属性slug(比如属性slug是color,则填pa_color)
    • 直接使用统一类型值'product_attribute'
  3. $return_original_if_missing:布尔值,若目标语言无对应翻译,是否返回原始ID(默认值为FALSE)
  4. $language_code:目标语言的代码(可选,留空则默认使用当前站点的语言)

正确实现代码示例

// 假设已获取目标属性对象$attribute,以及目标语言代码$target_lang
$translated_attr_id = apply_filters('wpml_object_id', $attribute->id, 'product_attribute', FALSE, $target_lang);

// 获取到翻译后的属性ID后,读取属性名称
if ($translated_attr_id) {
    $translated_attr = get_term($translated_attr_id, 'pa_' . $attribute->slug);
    $translated_attr_name = $translated_attr->name;
}

用wpml_translate_single_string直接翻译属性名称

如果不需要获取翻译后的属性ID,只想直接得到属性名称的翻译结果,可以用这个过滤器,注意文本域要指定为woocommerce:

$translated_attr_name = apply_filters('wpml_translate_single_string', $attribute->name, 'woocommerce', 'Product attribute ' . $attribute->slug);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:25:39