了解如何使用 WPML 翻译来自插件、主题以及您自行开发的简码。
借助 WPML,您可以翻译基于文本和基于 ID 的简码。基于文本的简码会输出文本,如下所示:
[goodmorning name="Dear client"]
另一方面,基于 ID 的简码使用其 ID 编号输出元素:
[myslider id="1"] [myslider id="2"]
在这里,每个简码输出不同的滑块。例如,一个可能输出英语滑块,另一个输出西班牙语滑块。
要翻译该简码,您需要将一个滑块的 ID 替换为另一个(例如,1 → 2)。
翻译来自兼容插件和主题的简码
要翻译来自兼容插件和主题的简码,请前往 WPML → 翻译仪表板,然后将包含简码的页面发送以供翻译。您的简码将与页面的其余内容一起显示在高级翻译编辑器中。
例如,以下简码在编辑器中的显示方式如下:
[goodmorning name="Dear client"]

如果您的简码包含链接(URL)属性,请使用搜索栏查找。WPML 默认会隐藏简码中的链接。

翻译来自不兼容插件和主题的简码
要翻译来自不兼容插件和主题的简码,您首先需要在 WPML 的自定义 XML 配置文件中注册它们。
请看这个包含两个简码的示例:
[fanpage link="https://example.com"]Some content[/fanpage] [goodmorning name="dear client" type="official"]
要在 WPML 中注册这些简码,我们将使用以下配置代码:
<wpml-config>
<shortcodes>
<shortcode>
<tag>goodmorning</tag>
<attributes>
<attribute>name</attribute>
<attribute>type</attribute>
</attributes>
</shortcode>
<shortcode>
<tag label="Fanpage shortcode">fanpage</tag>
<attributes>
<attribute>link</attribute>
</attributes>
</shortcode>
</shortcodes>
</wpml-config>
以下是 WPML 中配置的工作原理:
- 将所有简码放在 <shortcodes> 内
- 将各个简码设置包裹在 <shortcode> 内
- 使用 <tag> 定义简码名称,并根据需要包含自定义标签。这些标签会显示在高级翻译编辑器中的文本旁边。
- 使用 <attribute> 定义每个属性标题
- 使用 <attributes> 包裹所有属性
注册简码后,您可以通过 WPML → 翻译仪表板将它们与页面的其余内容一起翻译。
翻译自定义简码
要翻译您自行开发的自定义简码,您首先需要在 WPML 中注册它们。完成后,您就可以将它们与页面的其余内容一起翻译。
翻译简码内的硬编码文本
默认情况下,硬编码文本在 WPML 中不可翻译。要使其可翻译,您可以使用 Gettext 框架。请看这个示例,其中“Good morning”为硬编码文本:
function goodmorning_att($atts) {
$default = array(
'name' => 'there',
);
$a = shortcode_atts($default, $atts);
return 'Good morning, '.$a['name'];
}
add_shortcode('goodmorning', 'goodmorning_att');
要使“Good morning”可翻译,您可以调整代码以使用 Gettext:
function goodmorning_att($atts) {
$default = array(
'name' => 'there',
);
$a = shortcode_atts($default, $atts);
return __('Good morning, ', 'default').$a['name'];
}
add_shortcode('goodmorning', 'goodmorning_att');
这将使“Good morning”文本可翻译,并将其填充到字符串翻译中。
其他资源
要了解有关 wpml-config.xml 文件的更多信息,请访问语言配置文件指南。有关在 WPML 中配置其他元素的信息,请参阅我们的其他指南: