了解如何使用 gettext 函数,使主题和插件中的文本在 WPML 中可翻译。
要确保主题和插件中的文本可翻译,并在您的网站上正确显示,您需要满足两个条件:
- 将文本包含在 gettext 函数中
- 包含 text domain 参数
Gettext 基础知识
考虑以下属于“my-plugin-domain”域的字符串“Thank you!”:
__( 'Thank you!', 'my-plugin-domain' );
要将该字符串输出到浏览器,请使用 _e() 函数:
_e( 'Thank you!', 'my-plugin-domain' );
使用 HTML 时,请将其包含在 HTML 标签中:
<h2><?php _e( 'Thank you!', 'my-plugin-domain' ); ?></h2>
如果您有一个与周围文本分离的链接,请使用 esc_html_e() 函数:
<a href="http://wpml.org/" ><?php esc_html_e( 'Translated with WPML', 'my-domain' ); ?></a>
Gettext 最佳实践
1. 切勿将变量或常量包含在 gettext 函数中
这将导致字符串无法被扫描,从而无法翻译。
错误
<?php
if ( $morning ) {
define( 'GREETING', 'Good morning' );
} else {
define( 'GREETING', 'Good afternoon' );
}
_e( GREETING, 'my-domain' );
?>
正确
<?php
if ( $morning ) {
_e( 'Good morning', 'my-domain' );
} else {
_e( 'Good afternoon', 'my-domain' );
}
?>
2. 转义输出以确保安全
如果字符串直接在输出中渲染,请使用转义函数(如 esc_html_ 和 esc_attr_)来防范 XSS 攻击。
echo '<div>' . esc_html__( 'Back to homepage', 'my-domain' ) . '</div>';
3. 为译者添加注释
这有助于译者了解文本或变量出现的上下文。
/* translators: %1$s is status label (e.g. "active" and %2$s is quantity of bits/s (e.g. 12 Gbit/s) */ printf( esc_html__( 'State of your network is %1$s. Maximum download speed is %2$s.', 'my-plugin-domain' ), $state, $speed );
其他资源
要了解有关 gettext 的更多信息,请参阅官方 WordPress codex。