translate_user_role()
云策文档标注
概述
translate_user_role() 函数用于翻译用户角色名称,通过 gettext 机制从 POT 文件获取翻译,并处理旧格式的角色名以兼容性。它返回翻译后的角色名或原始名称。
关键要点
- 函数作用:翻译存储在数据库中的用户角色名称,确保国际化支持。
- 参数:$name(必需,角色名),$domain(可选,文本域,默认 'default')。
- 返回值:成功时返回翻译后的角色名,失败时返回原始名称。
- 兼容性处理:使用 before_last_bar() 处理旧格式角色名(如 'Role name|User role'),新安装不受影响。
- 内部实现:调用 translate_with_gettext_context() 进行上下文翻译。
代码示例
function translate_user_role( $name, $domain = 'default' ) {
return translate_with_gettext_context( before_last_bar( $name ), 'User role', $domain );
}注意事项
- 确保 $name 参数的首字母大写,否则可能返回原始名称而非翻译(例如,使用 'Administrator' 而非 'administrator')。
- 此函数主要用于后台管理界面,如 WP_Users_List_Table 和 wp_dropdown_roles()。
原文内容
Translates role name.
Description
Since the role names are in the database and not in the source there are dummy gettext calls to get them into the POT file and this function properly translates them back.
The before_last_bar() call is needed, because older installations keep the roles using the old context format: ‘Role name|User role’ and just skipping the content after the last bar is easier than fixing them in the DB. New installations won’t suffer from that problem.
Parameters
$namestringrequired-
The role name.
$domainstringoptional-
Text domain. Unique identifier for retrieving translated strings.
Default'default'.
Source
function translate_user_role( $name, $domain = 'default' ) {
return translate_with_gettext_context( before_last_bar( $name ), 'User role', $domain );
}
Skip to note 2 content
mahdiazarm
Always make sure that the first letter of
$nameis Capitalized!For example this will fail and return the original
$nametranslate_user_role( 'administrator' ); // return administratorbut this one will return the translation of
$nametranslate_user_role( 'Administrator' ); // return translation of Administrator