determine_locale()
云策文档标注
概述
determine_locale() 函数用于确定当前请求所需的区域设置(locale),返回字符串类型的区域标识。它通过一系列条件逻辑和过滤器钩子来动态决定区域,优先处理特定场景如登录页面、管理界面或安装模式。
关键要点
- 函数返回字符串类型的区域设置,用于本地化处理。
- 支持通过 pre_determine_locale 过滤器提前覆盖默认逻辑,实现短路返回。
- 在登录页面(wp-login.php)时,优先从 GET 参数 wp_lang 或 Cookie wp_lang 获取区域,并使用 sanitize_locale_name() 清理。
- 在管理界面(is_admin())或 JSON 请求中指定 _locale=user 时,使用 get_user_locale() 获取用户区域。
- 在安装模式(wp_installing())下,从 REQUEST 参数 language 或全局变量 $wp_local_package 获取区域。
- 如果以上条件均未满足,则回退到 get_locale() 获取默认区域。
- 最终通过 determine_locale 过滤器允许进一步修改区域设置。
代码示例
function determine_locale() {
$determined_locale = apply_filters( 'pre_determine_locale', null );
if ( $determined_locale && is_string( $determined_locale ) ) {
return $determined_locale;
}
// 条件逻辑处理...
if ( ! $determined_locale ) {
$determined_locale = get_locale();
}
return apply_filters( 'determine_locale', $determined_locale );
}注意事项
- 函数内部使用 sanitize_locale_name() 确保区域名称的安全性,避免无效字符。
- 钩子 pre_determine_locale 和 determine_locale 允许开发者自定义区域确定逻辑,增强灵活性。
- 相关函数如 get_user_locale()、wp_is_json_request() 等需在正确上下文中调用,以确保区域设置的准确性。
原文内容
Determines the current locale desired for the request.
Source
function determine_locale() {
/**
* Filters the locale for the current request prior to the default determination process.
*
* Using this filter allows to override the default logic, effectively short-circuiting the function.
*
* @since 5.0.0
*
* @param string|null $locale The locale to return and short-circuit. Default null.
*/
$determined_locale = apply_filters( 'pre_determine_locale', null );
if ( $determined_locale && is_string( $determined_locale ) ) {
return $determined_locale;
}
if (
isset( $GLOBALS['pagenow'] ) && 'wp-login.php' === $GLOBALS['pagenow'] &&
( ! empty( $_GET['wp_lang'] ) || ! empty( $_COOKIE['wp_lang'] ) )
) {
if ( ! empty( $_GET['wp_lang'] ) ) {
$determined_locale = sanitize_locale_name( $_GET['wp_lang'] );
} else {
$determined_locale = sanitize_locale_name( $_COOKIE['wp_lang'] );
}
} elseif (
is_admin() ||
( isset( $_GET['_locale'] ) && 'user' === $_GET['_locale'] && wp_is_json_request() )
) {
$determined_locale = get_user_locale();
} elseif (
( ! empty( $_REQUEST['language'] ) || isset( $GLOBALS['wp_local_package'] ) )
&& wp_installing()
) {
if ( ! empty( $_REQUEST['language'] ) ) {
$determined_locale = sanitize_locale_name( $_REQUEST['language'] );
} else {
$determined_locale = $GLOBALS['wp_local_package'];
}
}
if ( ! $determined_locale ) {
$determined_locale = get_locale();
}
/**
* Filters the locale for the current request.
*
* @since 5.0.0
*
* @param string $determined_locale The locale.
*/
return apply_filters( 'determine_locale', $determined_locale );
}
Hooks
- apply_filters( ‘determine_locale’, string $determined_locale )
-
Filters the locale for the current request.
- apply_filters( ‘pre_determine_locale’, string|null $locale )
-
Filters the locale for the current request prior to the default determination process.
Changelog
| Version | Description |
|---|---|
| 5.0.0 | Introduced. |