函数文档

get_locale()

💡 云策文档标注

概述

get_locale() 函数用于检索 WordPress 站点的当前区域设置(locale),通常返回如 'en_US' 或 'zh_CN' 的字符串。它通过检查全局变量、常量、数据库选项等来确定 locale,并始终通过 'locale' 过滤器钩子进行过滤。

关键要点

  • 函数返回当前站点的 locale 字符串,如 'en_US'。
  • locale 的确定过程包括:优先使用已设置的全局变量 $locale,否则检查 WPLANG 常量、多站点选项或单站点选项。
  • locale 始终通过 apply_filters('locale', $locale) 进行过滤,允许开发者通过 'locale' 钩子修改返回值。
  • 如果所有来源都为空,默认返回 'en_US'。
  • locale 获取过程应只执行一次,但每次调用都会应用过滤器。

代码示例

// 示例:获取当前 locale 并用于设置货币区域
setlocale( LC_MONETARY, get_locale() );
$my_local_settings = localeconv();
if ( $my_local_settings['int_curr_symbol'] == "" ) {
    setlocale( LC_MONETARY, 'en_US' );
}

📄 原文内容

Retrieves the current locale.

Description

If the locale is set, then it will filter the locale in the ‘locale’ filter hook and return the value.

If the locale is not set already, then the WPLANG constant is used if it is defined. Then it is filtered through the ‘locale’ filter hook and the value for the locale global set and the locale is returned.

The process to get the locale should only be done once, but the locale will always be filtered using the ‘locale’ hook.

Return

string The locale of the blog or from the ‘locale’ hook.

Source

function get_locale() {
	global $locale, $wp_local_package;

	if ( isset( $locale ) ) {
		/** This filter is documented in wp-includes/l10n.php */
		return apply_filters( 'locale', $locale );
	}

	if ( isset( $wp_local_package ) ) {
		$locale = $wp_local_package;
	}

	// WPLANG was defined in wp-config.
	if ( defined( 'WPLANG' ) ) {
		$locale = WPLANG;
	}

	// If multisite, check options.
	if ( is_multisite() ) {
		// Don't check blog option when installing.
		if ( wp_installing() ) {
			$ms_locale = get_site_option( 'WPLANG' );
		} else {
			$ms_locale = get_option( 'WPLANG' );
			if ( false === $ms_locale ) {
				$ms_locale = get_site_option( 'WPLANG' );
			}
		}

		if ( false !== $ms_locale ) {
			$locale = $ms_locale;
		}
	} else {
		$db_locale = get_option( 'WPLANG' );
		if ( false !== $db_locale ) {
			$locale = $db_locale;
		}
	}

	if ( empty( $locale ) ) {
		$locale = 'en_US';
	}

	/**
	 * Filters the locale ID of the WordPress installation.
	 *
	 * @since 1.5.0
	 *
	 * @param string $locale The locale ID.
	 */
	return apply_filters( 'locale', $locale );
}

Hooks

apply_filters( ‘locale’, string $locale )

Filters the locale ID of the WordPress installation.

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes