gettext 是一个非常不错的filter钩子,可以用来查找和替换本地化翻译文本,也就是替换 __()、_e()、_x()、_ex() 和 _n() 函数包含的文本。比如,你发现某个主题或插件的汉化文本不符合你的要求,但是你不想每次更新主题或插件后重新折腾语言包,那你就可以使用 gettext 钩子来自定义翻译文本。说了这么多,一起来看看例子吧,比较好理解。
比如 woocommerce 插件有一句文本是这样的:
<?php _e( 'Related Products', 'woocommerce' ); ?> |
<?php _e( 'Related Products', 'woocommerce' ); ?>
你可以使用下面的函数替换 ‘Related Products’ :
/**
* WordPress 使用 gettext 钩子替换<a href="https://www.wpdaxue.com/tag/%e6%9c%ac%e5%9c%b0%e5%8c%96" title="查看与【本地化】相关的文章" target="_blank" rel="noopener">本地化</a>翻译文本
* https://www.wpdaxue.com/gettext.html
*/
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
// 这是原来的文本
case 'Related Products' :
// 这是要替换的文本
$translated_text = __( 'Check out these related products', 'woocommerce' );
break;
}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 99, 3 ); |
/**
* WordPress 使用 gettext 钩子替换<a href="https://www.wpdaxue.com/tag/%e6%9c%ac%e5%9c%b0%e5%8c%96" title="查看与【本地化】相关的文章" target="_blank" rel="noopener">本地化</a>翻译文本
* https://www.wpdaxue.com/gettext.html
*/
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
// 这是原来的文本
case 'Related Products' :
// 这是要替换的文本
$translated_text = __( 'Check out these related products', 'woocommerce' );
break;
}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 99, 3 );
上面的代码就将 ‘Related Products’ 替换为 ‘Check out these related products’ 了,当然,你也可以修改为中文。
如果你要替换更多文本,按照 7-11 行代码复制修改一下即可。更多使用说明,请查看 gettext 文档
相关推荐:
来源:
https://www.wpdaxue.com/gettext.html
微信公众号
手机浏览(小程序)
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(): Failed to enable crypto in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57
Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32244.jpg): failed to open stream: operation failed in
/mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line
57